diff --git a/CODEOWNERS b/CODEOWNERS index 6a8730751d65c0cd83e109d7a4edffce37b988ec..59abea64af78d6f245925f04cb315afcb55bfac4 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -144,6 +144,8 @@ zh-cn/application-dev/telephony/ @zengyawen zh-cn/application-dev/dfx/ @zengyawen zh-cn/application-dev/database/ @ge-yafang zh-cn/application-dev/napi/drawing_guidelines.md @ge-yafang +zh-cn/application-dev/napi/native-window-guidelines.md @ge-yafang +zh-cn/application-dev/napi/mindspore-lite-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile_guidelines.md @HelloCrease zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih zh-cn/application-dev/background-task-management/ @RayShih @@ -164,60 +166,37 @@ zh-cn/application-dev/reference/arkui-js/ @HelloCrease zh-cn/application-dev/reference/arkui-ts/ @HelloCrease zh-cn/application-dev/reference/native-apis @RayShih zh-cn/application-dev/reference/native-lib @RayShih -zh-cn/application-dev/reference/apis/js-apis-DataUriUtils.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-ability.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-abilitystage.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-appmanager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-configuration.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-configurationconstant.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-featureAbility.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-formbindingdata.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-formextension.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-formerror.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-formhost.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-formInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-missionManager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-formprovider.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-uripermissionmanager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-Want.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-dataAbilityHelper.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-Context.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-ability-context.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegator.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-abilityMonitor.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-abilitystagecontext.md @RayShih +zh-cn/application-dev/quick-start/start-overview.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets-fa.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-js-fa.md @ge-yafang +zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang +zh-cn/application-dev/quick-start/package-structure.md @RayShih +zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih +zh-cn/application-dev/quick-start/syscap.md @RayShih +zh-cn/application-dev/napi/napi-guidelines.md @RayShih +zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang +zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease +zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease +zh-cn/application-dev/faqs/ @zengyawen +zh-cn/application-dev/file-management/ @qinxiaowang +zh-cn/application-dev/application-test/ @HelloCrease +zh-cn/application-dev/device-usage-statistics/ @HelloCrease + zh-cn/application-dev/reference/apis/js-apis-application-context.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-extension-context.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-extensionrunninginfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-formextensioncontext.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @RayShih zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md @RayShih zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @RayShih zh-cn/application-dev/reference/apis/js-apis-emitter.md @RayShih zh-cn/application-dev/reference/apis/js-apis-notification.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-eventhub.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-Bundle.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-zlib.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-zlib.md @RayShih @shuaytao @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-animator.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-prompt.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-prompt.md @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease @qieqiewl @tomatodevboy @niulihua zh-cn/application-dev/reference/apis/js-apis-display.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang @@ -231,7 +210,7 @@ zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-camera.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-image.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-media.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-i18n.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-intl.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @HelloCrease @@ -277,15 +256,14 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-tagSession.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-tagSession.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @RayShih zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-wifi.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-wifiext.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-wifi.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-wifiext.md @RayShih zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hichecker.md @zengyawen @@ -293,31 +271,31 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-system-time.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-system-time.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-battery-info.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-brightness.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-device-info.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-device-manager.md -zh-cn/application-dev/reference/apis/js-apis-geolocation.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-geolocation.md @RayShih zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-power.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-runninglock.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-power.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-runninglock.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-sensor.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-thermal.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-thermal.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-update.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-usb.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.mdd @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-vibrator.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-appAccount.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @zengyawen @@ -348,24 +326,134 @@ zh-cn/application-dev/reference/apis/js-apis-uitest.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease -zh-cn/application-dev/quick-start/start-overview.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js-low-code.md @ge-yafang -zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang -zh-cn/application-dev/quick-start/package-structure.md @RayShih -zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih -zh-cn/application-dev/quick-start/syscap.md @RayShih -zh-cn/application-dev/napi/napi-guidelines.md @RayShih -zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang -zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen -zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease -zh-cn/application-dev/website.md @zengyawen -zh-cn/application-dev/faqs/ @zengyawen +zh-cn/application-dev/reference/apis/js-apis-animator.md @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease @qieqiewl @tomatodevboy @niulihua zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @zengyawen -zh-cn/application-dev/reference/apis/Readme-CN.md @zengyawen \ No newline at end of file +zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen +zh-cn/application-dev/reference/apis/development-intro.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-Metadata.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bytrace.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-dispatchInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-inputevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-keycode.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-keyevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-logs.md @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-nfcController.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfctech.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-pointer.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-app.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-system-battery.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-device.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-file.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-location.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-system-network.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-notification.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-package.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @HelloCrease @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-system-request.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-router.md @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/reference/apis/js-apis-system-timer.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-touchevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-bundle-PackInfo.md @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-net-policy.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-net-statistics.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-tlsSocket.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-cooperate.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-webview.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-ability-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-abilitystagecontext.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-accessibility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-ability.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegator.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-abilityMonitor.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-abilitystage.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-Want.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-appmanager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-configuration.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-configurationconstant.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-Context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationResult.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-dataAbilityHelper.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-DataUriUtils.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-errorManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-extension-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-extensionrunninginfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-featureAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-formbindingdata.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-formerror.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-formextension.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-formextensioncontext.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-formhost.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-formInfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-formprovider.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-missionManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen + diff --git a/README_zh.md b/README_zh.md index ebf1bc8d7557d35f99eaacf8fd1427972d61d3b0..386fa1d7449553f92f399839d947a0dacd4e18b8 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,15 +18,15 @@ - master:最新开发版本。 - - OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。 + - OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - 该已更新至OpenHarmony 3.1.1 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.1-release.md)了解版本详情。 + 该版本已更新至OpenHarmony 3.1.3 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.3-release.md)了解版本详情。 - OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。 - 该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。 + 该版本已更新至OpenHarmony 3.0.6 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md)了解版本详情。 - OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。 @@ -34,7 +34,7 @@ ### 历史稳定版本 -OpenHarmony_v1.x_release:OpenHarmony 1.1.4 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md)了解版本详情。 +OpenHarmony_v1.x_release:OpenHarmony 1.1.5 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md)了解版本详情。 如需了解更多版本详情,点击[此处](zh-cn/release-notes/)。 diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index f3fa0e7ac0e9b829f2418e4b1bf96001e66553d2..ca2c2fda1462b991f8ea60f36b5c181783034874 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -16,6 +16,7 @@ - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [SysCap](quick-start/syscap.md) - [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md) + - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) @@ -26,6 +27,7 @@ - [Security](security/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md) - [Data Management](database/Readme-EN.md) + - [File Management](file-management/Readme-EN.md) - [Telephony](telephony/Readme-EN.md) - [Task Management](task-management/Readme-EN.md) - [Device Management](device/Readme-EN.md) diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability/ability-brief.md index 0d2303bf4f84c2ddc6f34a13d28b02a3762893b0..f0eb1ad833dfd7e21d275d48d40715221c542a50 100644 --- a/en/application-dev/ability/ability-brief.md +++ b/en/application-dev/ability/ability-brief.md @@ -5,7 +5,7 @@ An ability is the abstraction of a functionality that an application can provide The ability framework model has two forms: - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. -- Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more. +- Stage model, which is introduced since API version 9. In the stage model, there is `PageAbility` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability/context-userguide.md index d3e681244166cafecff86575dd1850db4ebf7f90..d5cd52e64ed5064ded90efea7d60898e1c2ee96c 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability/context-userguide.md @@ -56,7 +56,7 @@ The methods are used to set the display orientation of the current ability. **Example** ```javascript import featureAbility from '@ohos.ability.featureAbility' -import bundle from '../@ohos.bundle'; +import bundle from '@ohos.bundle'; export default { onCreate() { @@ -79,7 +79,7 @@ The following describes the contexts provided by the stage model in detail. ### application/Context -**application/Context** is the base class context that provides basic application information such as **resourceManager**, **applicationInfo**, **cacheDir**, and **area**. It also provides basic application methods such as **createBundleContext**. +**application/Context** is the base class context. It provides basic application information, such as **resourceManager**, **applicationInfo**, **cacheDir**, and **area**. It also provides basic application methods such as **createModuleContext**. **d.ts statement** @@ -235,13 +235,13 @@ export default class MainAbility extends Ability { For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). -### Obtaining the Context on an eTS Page +### Obtaining the Context on an ArkTS Page -In the stage model, in the `onWindowStageCreate` lifecycle of an ability, you can call `SetUIContent` of `WindowStage` to load an eTS page. In some scenarios, you need to obtain the context on the page to call related APIs. +In the stage model, in the `onWindowStageCreate` lifecycle of an ability, you can call `SetUIContent` of `WindowStage` to load an ArkTS page. In some scenarios, you need to obtain the context on the page to call related APIs. **How to Obtain** -Use the API described in the table below to obtain the context associated with an eTS page. +Use the API described in the table below to obtain the context associated with an ArkTS page. | API | Description | | :------------------------------------ | :--------------------------- | diff --git a/en/application-dev/ability/fa-brief.md b/en/application-dev/ability/fa-brief.md index b89c15504376f326629dd2b3dd537e1633d986d0..598ff0f5a79488925cc63d5b29afb0eaa86877aa 100644 --- a/en/application-dev/ability/fa-brief.md +++ b/en/application-dev/ability/fa-brief.md @@ -12,6 +12,7 @@ The Feature Ability (FA) model applies to application development using API vers ## Lifecycle Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and acts as a touchpoint for interacting with users. + **The following figure shows the lifecycle of the Page ability.** ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) @@ -26,3 +27,9 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other. ![fa-threading-model](figures/fa-threading-model.png) + +## Application Package Structure + +For details about the project directory structure of the FA model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section4154183910141). + +For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/package-structure.md). diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 48270359d9d49f9ea7d7111b021cd8b81da3df82..3bafb0bc097f0277f88ff4489c2731afdad6569e 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -92,7 +92,7 @@ After the preceding code is executed, the **startAbility()** API is called to st - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. - If the Service ability is running, the system directly calls **onCommand()** on the Service ability. -The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability-applying-only-to-system-applications). +The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability). ```javascript import featureAbility from '@ohos.ability.featureAbility'; diff --git a/en/application-dev/ability/figures/contextIntroduction.png b/en/application-dev/ability/figures/contextIntroduction.png index 7345a1a5a6a3471782e9399129c98f3d529bbfd5..50ec4d39f722431513051be8f6674f15307117f4 100644 Binary files a/en/application-dev/ability/figures/contextIntroduction.png and b/en/application-dev/ability/figures/contextIntroduction.png differ diff --git a/en/application-dev/ability/figures/favsstage.png b/en/application-dev/ability/figures/favsstage.png index 45f6b0ef255b01730dc42023430391e1141291c2..13b1766da57d89f206068dbb03741ba1f0ae96ff 100644 Binary files a/en/application-dev/ability/figures/favsstage.png and b/en/application-dev/ability/figures/favsstage.png differ diff --git a/en/application-dev/ability/figures/lifecycle.png b/en/application-dev/ability/figures/lifecycle.png index 694238d99c7e70d16d6bd1a37c86bcd599a9b2f3..345dd474c68069251a2c4ce8c9e8d792dbe029ef 100644 Binary files a/en/application-dev/ability/figures/lifecycle.png and b/en/application-dev/ability/figures/lifecycle.png differ diff --git a/en/application-dev/ability/figures/stageabilitylifecyclecallback.png b/en/application-dev/ability/figures/stageabilitylifecyclecallback.png index 9e17ed71f1dc9d118a490109c1e5181d738e63db..8dbfac680bc9ce6e0509ebc19bfc0ca035187c90 100644 Binary files a/en/application-dev/ability/figures/stageabilitylifecyclecallback.png and b/en/application-dev/ability/figures/stageabilitylifecyclecallback.png differ diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index fcd7a5dcfdde6547237f34f83dbb9bf2488d2255..3457aa29249a7c569053a09b6374cf03ce0d8868 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -12,8 +12,8 @@ An ability can be launched in the **standard**, **singleton**, or **specified** | Launch Type | Description |Action | | ----------- | ------- |---------------- | -| standard | Multi-instance | A new instance is started each time an ability starts.| -| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| +| standard | Standard mode. | A new instance is started each time an ability starts.| +| singleton | Singleton mode. | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| By default, the singleton mode is used. The following is an example of the `module.json5` file: diff --git a/en/application-dev/ability/stage-brief.md b/en/application-dev/ability/stage-brief.md index 0b4bfe8e3ec2943528e3bd2e8b640dea4ffbd070..427495774aa06066f6fd38c972ef59eafb102cf3 100644 --- a/en/application-dev/ability/stage-brief.md +++ b/en/application-dev/ability/stage-brief.md @@ -49,6 +49,8 @@ The ability and ability stage lifecycles are the rudiments of the basic process To implement device-specific tailoring and multi-window scalability, OpenHarmony decouples the component manager from the window manager. The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI content are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background changes, so the component manager only senses the foreground and background changes but not the focus changes. +There are two lifecycle states related to **WindowStage** in **Ability**: **onWindowStageCreate** and **onWindowStageDestroy**. They are valid only for devices with the window display capability. **onWindowStageCreate** is invoked when a window stage is created, where you can call **loadContent** to set pages to be loaded for the ability. **onWindowStageDestroy** is invoked when the window stage is destroyed, where you can release resources. + ## Ability Instances and Missions @@ -58,7 +60,7 @@ Abilities can be started in any of the following modes: + **Standard**: Each time **startAbility** is called, an instance of the specified ability type is created in the application process. **Ability2** in the figure below is started in standard mode. -+ **Specified**: Before creating an **AbilityRecord**, you can create a key for the instance. Each time **startAbility** is called, the system asks the application which ability instance (corresponding to a key) will be used. **Ability3** in the figure below is started in specified mode. ++ **Specified**: Before creating an **Ability** instance, you can create a key for the instance. Each time **startAbility** is called, the system asks the application which ability instance (corresponding to a key) will be used. **Ability3** in the figure below is started in specified mode. Each ability instance corresponds to a mission in **Launcher Recent**. @@ -92,6 +94,12 @@ All OpenHarmony applications are designed to meet the single-process model. In t - Render process: created for the WebView and used to load the WebView rendering library. - The following figure shows the process model of an application. +The following figure shows the process model of an application. + +![stageprocessmodel](figures/stageprocessmodel.png) + +## Application Package Structure + +For details about the project directory structure of the stage model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section56487581904). - ![stageprocessmodel](figures/stageprocessmodel.png) +For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File (Stage Model)](../quick-start/stage-structure.md). diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 6ddf26b87022c8bf098efc72de9ae4b4c0e28779..da1a7e1c517f284037a41a88e2167b6d1d2406aa 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -12,7 +12,7 @@ To use related APIs, you must declare the **ohos.permission.INTERNET** permissio For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md). -The following table describes the related APIs. +The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). | API | Description | | ----------------------------------------- | --------------------------------------------------------- | diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index 495f3b538b48b22d2d97f213d0e32189be799560..064c3e393fe27cedceb1f3f7d2d1e03b8ec22db6 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -52,9 +52,9 @@ Examples are given below. 3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. ```ts - let DB_NAME = "DB00.db"; - let TBL_NAME = "TBL00"; - let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + const DB_NAME = "DB00.db"; + const TBL_NAME = "TBL00"; + const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + TBL_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; @@ -132,9 +132,9 @@ Examples are given below. 1. Import the dependencies. ```ts - import Ability from '@ohos.application.Ability' - import dataShare from '@ohos.data.dataShare' - import dataSharePredicates from '@ohos.data.dataSharePredicates' + import Ability from '@ohos.application.Ability'; + import dataShare from '@ohos.data.dataShare'; + import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` 2. Define the URI string for communicating with the data provider. @@ -164,29 +164,25 @@ Examples are given below. ```ts // Construct a piece of data. - var valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; - var updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; - let da = new dataSharePredicates.DataSharePredicates(); - var valArray = new Array("*"); - let people = new Array( - { "name": "LiSi", "age": 41, "Binary": ar }, - { "name": "WangWu", "age": 21, "Binary": arr }, - { "name": "ZhaoLiu", "age": 61, "Binary": arr }); + let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; + let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; + let predicates = new dataSharePredicates.DataSharePredicates(); + let valArray = new Array("*"); // Insert a piece of data. dsHelper.insert(dseUri, valuesBucket, (err, data) => { console.log("dsHelper insert result: " + data); }); - // Delete data. - dsHelper.delete(dseUri, da, (err, data) => { - console.log("dsHelper delete result: " + data); - }); // Update data. - dsHelper.update(dseUri, da, updateBucket, (err, data) => { + dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { console.log("dsHelper update result: " + data); }); // Query data. - dsHelper.query(dseUri, da, valArray, (err, data) => { + dsHelper.query(dseUri, predicates, valArray, (err, data) => { console.log("dsHelper query result: " + data); }); + // Delete data. + dsHelper.delete(dseUri, predicates, (err, data) => { + console.log("dsHelper delete result: " + data); + }); ``` diff --git a/en/application-dev/database/database-datashare-overview.md b/en/application-dev/database/database-datashare-overview.md index f603c4dd54840118471cba6c344de58121577d57..019adeb3fa6850ed5407e0107d5996054ef11de7 100644 --- a/en/application-dev/database/database-datashare-overview.md +++ b/en/application-dev/database/database-datashare-overview.md @@ -22,7 +22,7 @@ Before you get started, familiarize yourself with the following concepts: An application that accesses the data or services provided by a data provider. It is also called a client. -- Value bucket (**ValuesBucket**) +- **ValuesBucket** One or more data records stored in the form of key-value (KV) pairs. The keys are of the string type. The values can be of the number, string, Boolean, or Unit8Array type. diff --git a/en/application-dev/database/database-distributedobject-overview.md b/en/application-dev/database/database-distributedobject-overview.md index 80985ed39b8c91a5c9635e0be8fd00f4be2da702..9fb93eba7c13f85da0cdccb9036df26e4d8d8ce0 100644 --- a/en/application-dev/database/database-distributedobject-overview.md +++ b/en/application-dev/database/database-distributedobject-overview.md @@ -12,7 +12,7 @@ The distributed data object management framework provides object-oriented in-mem - **Distributed data object** - A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **put** and **get** operations in the corresponding database, respectively. + A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **get** and **put** operations in the corresponding database, respectively. The distributed data object can be in the following states in its lifecycle: diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index 61aa2294c3f8ee077241e347e47e7780f50c4359..c4f6250f5ae91a645fe6aba6b81ec98df8eb2329 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -88,15 +88,22 @@ Use the following APIs to delete a **Preferences** instance or data file. 2. Obtain a **Preferences** instance. Read the specified file and load its data to the **Preferences** instance for data operations. - + FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' - var context = featureAbility.getContext() - + let context = featureAbility.getContext(); + + let preferences = null; let promise = data_preferences.getPreferences(context, 'mystore'); + + promise.then((pref) => { + preferences = pref; + }).catch((err) => { + console.info("Failed to get the preferences."); + }) ``` Stage model: @@ -104,14 +111,21 @@ Use the following APIs to delete a **Preferences** instance or data file. ```ts // Obtain the context. import Ability from '@ohos.application.Ability' - var context - class MainAbility extends Ability{ + let context = null; + let preferences = null; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage){ - context = this.context + context = this.context; } } - + let promise = data_preferences.getPreferences(context, 'mystore'); + + promise.then((pref) => { + preferences = pref; + }).catch((err) => { + console.info("Failed to get the preferences."); + }) ``` 3. Write data. @@ -119,35 +133,27 @@ Use the following APIs to delete a **Preferences** instance or data file. Use the **preferences.put()** method to write data to the **Preferences** instance. ```js - promise.then((preferences) => { - let putPromise = preferences.put('startup', 'auto'); - putPromise.then(() => { - console.info("Put the value of 'startup' successfully."); - }).catch((err) => { - console.info("Failed to put the value of 'startup'. Cause: " + err); - }) + let putPromise = preferences.put('startup', 'auto'); + putPromise.then(() => { + console.info("Put the value of 'startup' successfully."); }).catch((err) => { - console.info("Failed to get the preferences."); + console.info("Failed to put the value of 'startup'. Cause: " + err); }) ``` - + 4. Read data. Use the **preferences.get()** method to read data. ```js - promise.then((preferences) => { - let getPromise = preferences.get('startup', 'default'); - getPromise.then((value) => { + let getPromise = preferences.get('startup', 'default'); + getPromise.then((value) => { console.info("The value of 'startup' is " + value); - }).catch((err) => { - console.info("Failed to get the value of 'startup'. Cause: " + err); - }) }).catch((err) => { - console.info("Failed to get the preferences.") - }); + console.info("Failed to get the value of 'startup'. Cause: " + err); + }) ``` - + 5. Store data persistently. Use the **flush()** method to flush data from the **Preferences** instance to its file. @@ -161,11 +167,12 @@ Use the following APIs to delete a **Preferences** instance or data file. Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. ```js - var observer = function (key) { + let observer = function (key) { console.info("The key" + key + " changed."); } preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { + // The data is changed from 'auto' to 'manual'. + preferences.put('startup', 'manual', function (err) { if (err) { console.info("Failed to put the value of 'startup'. Cause: " + err); return; diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index bd38925cbe8a17e5cb6319ffc9729ef263945e9c..70fb8cbbee58dd51b8edacf8f7d6bc58e874859d 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -140,7 +140,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md index f18f59468d0650400adfb50b87645c763a740b9c..60aa41fedd15531c583c48200eddc3c91e5a8fde 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md @@ -22,8 +22,8 @@ import stats from '@ohos.bundleState'; | function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.| | function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. | -| function getRecentlyUsedModules(callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **1000**.| -| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**.| +| function getRecentlyUsedModules(callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains a maximum of 1000 FA usage records. | +| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**, which cannot exceed 1000.| | function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries the number of notifications from all applications based on the specified start time and end time.| | function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.| | function queryAppUsagePriorityGroup(bundleName : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. This API uses an asynchronous callback to return the result.| @@ -326,14 +326,14 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - // Promise mode without parameters + // Promise mode when bundleName is not specified stats.queryAppUsagePriorityGroup().then(res => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch(err => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); }); - // Asynchronous callback mode without parameters + // Asynchronous callback mode when bundleName is not specified stats.queryAppUsagePriorityGroup((err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); @@ -341,16 +341,16 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); } }); - - // Promise mode with parameters - stats.queryAppUsagePriorityGroup(this.bundleName).then(res => { + let bundleName = "com.ohos.camera"; + // Promise mode when bundleName is specified + stats.queryAppUsagePriorityGroup(bundleName).then(res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch(err => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); }); - // Asynchronous callback mode with parameters - stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { + // Asynchronous callback mode when bundleName is specified + stats.queryAppUsagePriorityGroup(bundleName, (err, res) => { if (err) { console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); } else { @@ -437,3 +437,4 @@ import stats from '@ohos.bundleState'; } }); ``` + diff --git a/en/application-dev/device/device-location-overview.md b/en/application-dev/device/device-location-overview.md index aa619c4549083521dd6ac5bcc05795074adc9af4..a26f0c5a7003a14c13cf4fc697e3a55a202f1eec 100644 --- a/en/application-dev/device/device-location-overview.md +++ b/en/application-dev/device/device-location-overview.md @@ -15,15 +15,18 @@ Your application can call location-specific APIs to obtain the location informat Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors. - **Coordinate** + A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. - **GNSS positioning** GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. - **Base station positioning** + Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. - **WLAN or Bluetooth positioning** + WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. diff --git a/en/application-dev/device/sample-server-guidelines.md b/en/application-dev/device/sample-server-guidelines.md index 383894cb87dfea65ee6291836bc1928f8341a479..faf07d1e82bed9aa679901add578df1aae2444fc 100644 --- a/en/application-dev/device/sample-server-guidelines.md +++ b/en/application-dev/device/sample-server-guidelines.md @@ -2,7 +2,7 @@ ## When to Use -The sample server provides a package search server for checking update packages and obtaining the update package download URLs, which was previously unavailable in the real-world update service. The sample server supports update service testing and secondary development function verification, building an end-to-end environment to cater for diverse update service use cases. +The sample server provides a package search server for checking update packages and obtaining the update package download URLs, which was previously unavailable in the real-world update service. The sample server supports update service testing and functional verification for secondary development, building an end-to-end environment to cater for diverse update service use cases. ## How to Develop @@ -14,8 +14,6 @@ The sample server provides a package search server for checking update packages openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com" ``` - - 2. Modify the **bundle.json** file. Add **sub_component** to the **build** field. @@ -32,13 +30,13 @@ The sample server provides a package search server for checking update packages Go to the **update_updateservice** directory and run the following commands to create a code directory: ``` - mkdir server_sample // Create the server_sample folder. - touch server_sample/BUILD.gn // Create the BUILD.gn file. - mkdir server_sample/include // Create the include folder to store the header file of the sample server. - touch server_process.h // Create the server_process.h header file. - mkdir server_sample/src // Create the src folder to store the C/C++ files of the sample server. - touch server_sample/src/server_process.c // Create the server_process.c file. - touch server_sample/src/main.cpp // Create the main.cpp file. + mkdir server_sample // Create the server_sample folder. + touch server_sample/BUILD.gn // Create the BUILD.gn file. + mkdir server_sample/include // Create the include folder to store the header file of the sample server. + touch server_process.h // Create the server_process.h header file. + mkdir server_sample/src // Create the src folder to store the C/C++ files of the sample server. + touch server_sample/src/server_process.c // Create the server_process.c file. + touch server_sample/src/main.cpp // Create the main.cpp file. ``` 4. Write the **BUILD.gn** file. diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index d51625ccb9605fe2fb35b95f71eebc4e1607b753..eb023f7c782d8cb0e086819904b6def65da14214 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -38,7 +38,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat // Import the USB API package. import usb from '@ohos.usb'; // Obtain the USB device list. - var deviceList = usb.getDevices(); + let deviceList = usb.getDevices(); /* Example deviceList structure [ @@ -81,21 +81,21 @@ You can set a USB device as the USB host to connect to other USB devices for dat number: 1, type: 3, interfaceId: 0, - }, - ], - }, - ], - }, - ], - }, - ], + } + ] + } + ] + } + ] + } + ] */ ``` 2. Obtain the device operation permissions. ```js - var deviceName = deviceList[0].name; + let deviceName = deviceList[0].name; // Request the permissions to operate a specified device. usb.requestRight(deviceName).then(hasRight => { console.info("usb device request right result: " + hasRight); @@ -108,7 +108,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ```js // Open the device, and obtain the USB device pipe for data transfer. - var pipe = usb.connectDevice(deviceList[0]); + let pipe = usb.connectDevice(deviceList[0]); /* Claim the corresponding interface from deviceList. interface1 must be one present in the device configuration. @@ -127,7 +127,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => { if (dataLength >= 0) { console.info("usb readData result Length : " + dataLength); - var resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string. + let resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string. console.info("usb readData buffer : " + resultStr); } else { console.info("usb readData failed : " + dataLength); diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 48f725e080441281cd2e88820eeacc6032a2dbab..afda67ee6fdf21b3d91d525d397c956d98167e82 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -12,12 +12,10 @@ The following table provides only a brief description of related APIs. For detai **Table 1** APIs for application event logging -| API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. | -| write(string eventName, EventType type, object keyValues): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | -| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.| -| write(AppEventInfo info): Promise\ | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.| +| API | Description | +| ------------------------------------------------------------ | ---------------------------------------------------- | +| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.| +| write(AppEventInfo info): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | When an asynchronous callback is used, the return value can be processed directly in the callback. @@ -84,6 +82,7 @@ The following uses a one-time event watcher as an example to illustrate the deve .fontWeight(FontWeight.Bold) Button("1 writeTest").onClick(()=>{ + // Perform event logging based on the input event parameters. hiAppEvent.write({ domain: "test_domain", name: "test_event", @@ -100,6 +99,7 @@ The following uses a one-time event watcher as an example to illustrate the deve }) Button("2 addWatcherTest").onClick(()=>{ + // Add an event watcher based on the input subscription parameters. hiAppEvent.addWatcher({ name: "watcher1", appEventFilters: [{ domain: "test_domain" }], @@ -109,17 +109,23 @@ The following uses a one-time event watcher as an example to illustrate the deve timeOut: 2 }, onTrigger: function (curRow, curSize, holder) { + // If the holder object is null, return an error after recording it in the log. if (holder == null) { console.error("HiAppEvent holder is null"); return; } + // Set the size threshold to 1,000 bytes for obtaining an event package. + holder.setSize(1000); let eventPkg = null; + // Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained. while ((eventPkg = holder.takeNext()) != null) { - console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId); - console.info("HiAppEvent eventPkg.row=" + eventPkg.row); - console.info("HiAppEvent eventPkg.size=" + eventPkg.size); + // Parse the obtained event package and display the result on the Log page. + console.info('HiAppEvent eventPkg.packageId=' + eventPkg.packageId); + console.info('HiAppEvent eventPkg.row=' + eventPkg.row); + console.info('HiAppEvent eventPkg.size=' + eventPkg.size); + // Traverse and parse event string arrays in the obtained event package. for (const eventInfo of eventPkg.data) { - console.info("HiAppEvent eventPkg.data=" + eventInfo); + console.info('HiAppEvent eventPkg.data=' + eventInfo); } } } @@ -127,6 +133,7 @@ The following uses a one-time event watcher as an example to illustrate the deve }) Button("3 removeWatcherTest").onClick(()=>{ + // Remove the specified event watcher. hiAppEvent.removeWatcher({ name: "watcher1" }) diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md index 316ee1b07898a24721b81625c2e9193ae08aa85f..1b45886ca4c593bbfff1b1b07d5892ad20ba58ae 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-guidelines.md @@ -12,7 +12,7 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de | API| Return Value| Description| | ---------------------------------------------------------------------------- | --------- | ------------ | -| hiTraceMeter.startTrace(name: string, taskId: number, expectedTime?: number) | void | Starts a trace task. 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 task ID can be used.| +| hiTraceMeter.startTrace(name: string, taskId: number) | void | Starts a trace task. 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 task ID can be used.| | hiTraceMeter.finishTrace(name: string, taskId: number) | void | Stops a trace task. The values of **name** and **taskId** must be the same as those of **hiTraceMeter.startTrace**.| | hiTraceMeter.traceByValue(name: string, value: number) | void | Traces the value changes of a variable.| @@ -31,10 +31,6 @@ In this example, distributed call chain tracing begins when the application star }, onInit() { this.title = this.$t('strings.world'); - - // The expected duration of the trace task is 5 ms. - hiTraceMeter.startTrace("business", 1); - hiTraceMeter.startTrace("business", 1, 5); // Start track tasks with the same name concurrently. hiTraceMeter.startTrace("business", 1); diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index dc45ed9db0eec504b1ff6f535babf11265f2df91..c0b69b85a868f8afd7a7f627fb0275f46cbc87fc 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -1,19 +1,15 @@ # FAQs - [Ability Framework Development](faqs-ability.md) -- [Data Management Development](faqs-data-management.md) -- [File Management Development](faqs-file-management.md) -- [Graphics and Image Development](faqs-graphics.md) -- [hdc_std Command Usage](faqs-ide.md) -- [IDE Usage](faqs-hdc-std.md) - [ArkUI (JavaScript) Development](faqs-ui-js.md) - [ArkUI (eTS) Development](faqs-ui-ets.md) - [Graphics and Image Development](faqs-graphics.md) - [File Management Development](faqs-file-management.md) +- [Network and Connection Development](faqs-connectivity.md) - [Data Management Development](faqs-data-management.md) - [Device Management Development](faqs-device-management.md) - [Native API Usage](faqs-native.md) -- [Network and Connection Development](faqs-connectivity.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) +- [hdc_std Command Usage](faqs-ide.md) +- [IDE Usage](faqs-hdc-std.md) - [Development Board](faqs-development-board.md) - diff --git a/en/application-dev/faqs/faqs-connectivity.md b/en/application-dev/faqs/faqs-connectivity.md index 3b8dea82129c03f0dc12c12296a28b9a0c46c99b..e3b02269e2de947fb4ab4069f1d7ba4812825ddc 100644 --- a/en/application-dev/faqs/faqs-connectivity.md +++ b/en/application-dev/faqs/faqs-connectivity.md @@ -19,7 +19,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 -Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a libcurl library operation timeout. For details, see any HTTP status code description available. +Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) diff --git a/en/application-dev/faqs/faqs-ui-ets.md b/en/application-dev/faqs/faqs-ui-ets.md index fd21421cd95edc2bc838b8401724fae10448d9fd..86a05c91851d6844dcc08e368d81b936b7d1b8ac 100644 --- a/en/application-dev/faqs/faqs-ui-ets.md +++ b/en/application-dev/faqs/faqs-ui-ets.md @@ -202,7 +202,7 @@ struct DialogTest { Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -The **\** component is a scrollable container. By default, it taks up the entire screen height. When any component with a fixed height takes up part of the screen height, you need to explicitly specify **layoutWeight(1)** for the parent container of the **\** component to take up the remaining height instead of the entire screen height. +The **\** component is a scrollable container. By default, it takes up the entire screen height. When any component with a fixed height takes up part of the screen height, you need to explicitly specify **layoutWeight(1)** for the parent container of the **\** component to take up the remaining height instead of the entire screen height. ## How do I center child components in a grid container? diff --git a/en/application-dev/faqs/faqs-ui-js.md b/en/application-dev/faqs/faqs-ui-js.md index 5d39db33199fddf298e66e4bd290999b58d6dddb..7d4ae1dcb80b63a4632e3a30627ff53f37e63c37 100644 --- a/en/application-dev/faqs/faqs-ui-js.md +++ b/en/application-dev/faqs/faqs-ui-js.md @@ -30,7 +30,7 @@ let options = {trim : false, declarationKey:"_declaration", nameKey : "_name", elementsKey : "_elements"} let result:any = conv.convert(xml, options) // Convert fields in the XML file into JavaScript objects. console.log('Test: ' + JSON.stringify(result)) -console.log('Test: ' + result._declaration._attributes.version) // vesion field in XML file +console.log('Test: ' + result._declaration._attributes.version) // version field in XML file console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // title field in XML file ``` diff --git a/en/application-dev/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..4bb5fe54817e245807612eaac1a0b6d235101f7a --- /dev/null +++ b/en/application-dev/file-management/Readme-EN.md @@ -0,0 +1,6 @@ +# File Management +- MediaLibrary Management + - [MediaLibrary Overview](medialibrary-overview.md) + - [Media Asset Management](medialibrary-resource-guidelines.md) + - [File Path Management](medialibrary-filepath-guidelines.md) + - [Album Management](medialibrary-album-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/file-management/medialibrary-album-guidelines.md b/en/application-dev/file-management/medialibrary-album-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..322e596ef6a0776291ab36529fb10760c09b4c51 --- /dev/null +++ b/en/application-dev/file-management/medialibrary-album-guidelines.md @@ -0,0 +1,94 @@ +# Album Management + +You can use the APIs provided by the **mediaLibrary** module to create and delete an album and obtain images in the album. + +> **NOTE** +> +> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. + +To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). + +## Obtaining Images and Videos in an Album + +You can obtain images and videos in an album in either of the following ways: + +- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified to obtain the media assets. For details, see [Querying Media Assets with the Specified Album Name](medialibrary-resource-guidelines#querying-media-assets-with-the-specified-album-name). + +- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. For details, see [Obtaining Images and Videos in an Album](medialibrary-resource-guidelines#obtaining-images-and-videos-in-an-album). + +## Creating an Album + +You can use [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1), with the relative path set, to create an album while adding a media asset to the album. The relative path is the album name. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to create an album named **myAlbum**. + +**How to Develop** + +1. Call **getPublicDirectory** to obtain the public directory that stores files of a certain type. + + For details about the operation, see [Obtaining a Public Directory](medialibrary-filepath-guidelines.md#obtaining-a-public-directory). + +2. Call **createAsset** to create an image, with the relative path set to **path + 'myAlbum/'**. + + This operation creates an album and adds an image to it. + +```ts +async function example() { + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_IMAGE) + // myAlbum is the path for storing the new file and the name of the new album. + media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createAlbum successfully, message = ' + fileAsset); + } else { + console.info('createAlbum failed, message = ' + err); + } + }); +} +``` + +## Renaming an Album + +Renaming modifies the **FileAsset.albumName** attribute of the album, that is, the album name. After the modification, call [Album.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-3) to commit the modification to the database. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to rename the album **newAlbum**. + +**How to Develop** + +1. Create a retrieval condition for obtaining the target album. +2. Call **getAlbums** to obtain the album list. +3. Rename the album **newAlbum**. +4. Call **Album.commitModify** to commit the modification of the attributes to the database. + +```ts +async function example() { + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let albumList = await media.getAlbums(AlbumNoArgsfetchOp); + let album = albumList[0]; + album.albumName = 'newAlbum'; + // Void callback. + album.commitModify().then(function() { + console.info("albumRename successfully"); + }).catch(function(err){ + console.info("albumRename failed with error:"+ err); + }); +} +``` diff --git a/en/application-dev/file-management/medialibrary-filepath-guidelines.md b/en/application-dev/file-management/medialibrary-filepath-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..fc9b327031cfee8ea6de601b3c3d268bbf161c53 --- /dev/null +++ b/en/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -0,0 +1,244 @@ +# File Path Management + +User data on OpenHarmony is managed by the **mediaLibrary** module in a unified manner. You can use the APIs provided by this module to access and operate the user data. + +> **NOTE** +> +> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. + +To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). + +## File Formats Supported by Public Directories + +Before using file paths for development, learn the file formats supported by each public directory. +> **CAUTION** +> +> The following table lists only the file types that can be identified by the system. In your application development, pay attention to the file formats supported by the corresponding interfaces.
For example, only .jpeg and .webp can be used for image encoding, and only .jpg, .png, .gif, .bmp, .webp, and .raw can be used for image decoding. + +| Directory | Directory Type | Media Type | Description | Supported File Format | +| ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ | +| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv | +| Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv | +| Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif | +| Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg | +| Documents/ | DIR_DOCUMENTS | FILE |Dedicated file directory. Only files except audios, images, and videos can be stored in this directory and its subdirectories.| - | +| Download/ | DIR_DOWNLOAD | ALLTYPE |Directory for storing downloaded files. The types of files in this directory and its subdirectories are not restricted.| - | + +## Obtaining a Public Directory + +Different types of files are stored in different public directories. You can call [getPublicDirectory](../reference/apis/js-apis-medialibrary.md#getpublicdirectory8-1) to obtain the public directory that stores files of a certain type. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +The following describes how to obtain the public directory that stores camera files. + +```ts +async function example(){ + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; + const dicResult = await media.getPublicDirectory(DIR_CAMERA); + if (dicResult == 'Camera/') { + console.info('mediaLibraryTest : getPublicDirectory passed'); + } else { + console.info('mediaLibraryTest : getPublicDirectory failed'); + } +} +``` + +## Copying Files Between the Application Sandbox and the Public Directory + +OpenHarmony provides the application sandbox to minimize the leakage of application data and user privacy information. + +Users can access files stored in the public directories through the system applications **Files** and **Gallery**. However, files in the application sandbox can be accessed only by the application itself. + +### Copying a File + +You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. + +You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. +- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. + +**How to Develop** + +1. Call [Context.getFilesDir](../reference/apis/js-apis-Context.md#contextgetfilesdir) to obtain the directory of the application sandbox. +2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. +3. Call **fileio.open** to open the file in the sandbox. +4. Call **fileAsset.open** to open the file in the public directory. +5. Call **fileio.copyfile** to copy the file. +6. Call **fileAsset.close** and **fileio.close** to close the file. + +**Example 1: Copying Files from the Public Directory to the Sandbox** + +```ts +async function copyPublic2Sandbox() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let sandboxDirPath = globalThis.context.filesDir; + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + + let fdPub = await fileAsset.open('rw'); + let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); + await fileio.copyFile(fdPub, fdSand); + + await fileAsset.close(fdPub); + await fileio.close(fdSand); + + let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); + console.log('content read from sandbox file: ', content_sand) +} +``` + +**Example 2: Copying a File from the Sandbox to the Public Directory** + +```ts +async function copySandbox2Public() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let sandboxDirPath = globalThis.context.filesDir; + + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); + try { + let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); + console.info('createFile successfully, message = ' + fileAsset); + } catch (err) { + console.info('createFile failed, message = ' + err); + } + try { + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile02.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + var fileAsset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('file asset get failed, message = ', err) + } + var fdPub = await fileAsset.open('rw'); + var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); + await fileio.copyFile(fdSand, fdPub); + await fileio.close(fdPub); + await fileio.close(fdSand); + let fdPubRead = await fileAsset.open('rw'); + try { + var arrayBuffer = new ArrayBuffer(4096); + await fileio.read(fdPubRead, arrayBuffer); + var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer)); + fileAsset.close(fdPubRead); + } catch (err) { + console.log('read text failed, message = ', err); + } + console.log('content read from public file: ', content_pub); +} +``` + +### Reading and Writing a File + +You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. +- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. + +**How to Develop** + +1. Create a file. + + ```ts + async function example() { + let mediaType = mediaLibrary.MediaType.FILE; + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_DOCUMENTS); + media.createAsset(mediaType, "testFile.text", path).then (function (asset) { + console.info("createAsset successfully:"+ JSON.stringify(asset)); + }).catch(function(err){ + console.info("createAsset failed with error:"+ err); + }); + } + ``` + +2. Call **FileAsset.open** to open the file. + +3. Call **fileio.write** to write a string to the file. + +4. Call **fileio.read** to read the file and save the data read in an array buffer. + +5. Convert the array buffer to a string. + +6. Use **FileAsset.close** to close the file. + +**Example 1: Opening an Existing File and Writing Data to It** + +```ts +async function writeOnlyPromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAssetName: ', fileAsset.displayName); + + try { + let fd = await fileAsset.open('w'); + console.info('file descriptor: ', fd); + await fileio.write(fd, "Write file test content."); + await fileAsset.close(fd); + } catch (err) { + console.info('write file failed, message = ', err); + } +} +``` + +**Example 2: Opening an Existing File and Reading Data from It** + +```ts +async function readOnlyPromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAssetName: ', fileAsset.displayName); + + try { + let fd = await fileAsset.open('r'); + let arrayBuffer = new ArrayBuffer(4096); + await fileio.read(fd, arrayBuffer); + let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); + globalThis.fileContent = fileContent + globalThis.fileName = fileAsset.displayName; + console.info('file content: ', fileContent); + await fileAsset.close(fd); + } catch (err) { + console.info('read file failed, message = ', err); + } +} +``` diff --git a/en/application-dev/file-management/medialibrary-overview.md b/en/application-dev/file-management/medialibrary-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..79f13fe066967607ab15f096fe3ce5478aaa9abe --- /dev/null +++ b/en/application-dev/file-management/medialibrary-overview.md @@ -0,0 +1,127 @@ +# MediaLibrary Development Overview + +The **mediaLibrary** module provides APIs for you to access and modify media files. + +- You can manage [media assets (audios, videos, image, and files)](medialibrary-resource-guidelines.md) as follows: + - Query media assets. + - Obtain an image or a video. + - Obtain the thumbnail of an image or a video. + - Create a media asset. + - Rename a media asset. + - Move a media asset to the recycle bin. +- You can manage [file paths](medialibrary-filepath-guidelines.md) as follows: + - Obtain the public directory that stores files of a certain type. + - Copy files between the application sandbox and the public directory. + - Read and write a file. +- You can manage [albums](medialibrary-album-guidelines.md) as follows: + - Obtain images and videos in an album. + - Create an album. + - Rename an album. + +> **NOTE** +> +> This development guide applies only to the stage model (available from API version 9). + +To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. + +Before using the **MediaLibrary** APIs to develop features, you must learn how to: + +- [Obtain a MediaLibrary Instance](#obtaining-a-medialibrary-instance) +- [Request Permissions](#requesting-permissions) + +## Obtaining a MediaLibrary Instance + +An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) to obtain a **MediaLibrary** instance based on the application context. Through this instance, the application can access and modify personal media data (such as audios, videos, images, and files). + +**How to Develop** + +1. Import the **mediaLibrary** module. +2. Call **getContext** to obtain the application context. +3. Obtain a **MediaLibrary** instance. + +```ts +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; + +const context = getContext(this); +var media = mediaLibrary.getMediaLibrary(context); +``` + +## Requesting Permissions + +To read and write a **MediaLibrary** instance, you must have the required permissions, as described in the table below. Before requesting the permissions, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met. + +| Permission | Description | Authorization Mode | +| ------------------------------ | ------------------------------------------ | ---------- | +| ohos.permission.READ_MEDIA | Allows an application to read media files from the user's external storage.| user_grant | +| ohos.permission.WRITE_MEDIA | Allows an application to read media files from and write media files into the user's external storage.| user_grant | +| ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant | + +After configuring the permissions in the **module.json5** file, the application must call [Context.requestPermissionsFromUser](../reference/apis/js-apis-ability-context.md#abilitycontextrequestpermissionsfromuser) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. + +> **NOTE**
Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**. + +**How to Develop** + +1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md). + + ```json + { + "module": { + "requestPermissions": [ + { + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.READ_MEDIA", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.WRITE_MEDIA", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "always" + } + } + ] + } + } + ``` + +2. Call **requestPermissionsFromUser** to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. + + ```ts + import Ability from '@ohos.application.Ability' + + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] + var permissionRequestResult; + this.context.requestPermissionsFromUser(permissions,(err,result) => { + if(err){ + console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); + }else{ + permissionRequestResult=result; + console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); + } + }); + } + } + ``` + + diff --git a/en/application-dev/file-management/medialibrary-resource-guidelines.md b/en/application-dev/file-management/medialibrary-resource-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..737ea4e48fa24c38f47fe7595e9df6e1370ab69a --- /dev/null +++ b/en/application-dev/file-management/medialibrary-resource-guidelines.md @@ -0,0 +1,389 @@ +# Media Asset Management + +Your applications can use the APIs provided by the **mediaLibrary** module to perform operations on media assets such as audios, videos, images, and files. + +> **NOTE** +> +> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. + +To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). + +## Querying Media Assets + +You can query media assets by condition such as the media type, date, or album name. + +To do so, call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1), with a **MediaFetchOptions** object passed in to specify the conditions. In this object, **MediaFetchOptions.selections** are the retrieval conditions, and the enumerated values of **FileKey** are used as the column names of the conditions; **MediaFetchOptions.selectionArgs** are the values of the conditions. You can also specify **order** (sorting mode of the search result), **uri** (file URI), and **networkId** (network ID of the registered device) as the conditions. + +To obtain the object at the specified position (for example, the first, the last, or with the specified index) in the result set, call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7). In this section, **getNextObject** is used cyclically to obtain all media assets in the result set. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +### Querying Media Assets with the Specified Media Type + +The following describes how to obtain images. + +**How to Develop** + +To specify the media type as the retrieval condition, set **selections** to **FileKey.MEDIA_TYPE**. + +To specify the image as the media type, set **selectionArgs** to **MediaType.IMAGE**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.IMAGE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +### Querying Media Assets with the Specified Date + +The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions. + +To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**. + +To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let option = { + selections: fileKeyObj.DATE_ADDED + '= ?', + selectionArgs: ['2022-8-5'], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +### Querying Media Assets and Sorting Them + +The following describes how to query images and sort them in descending order by the date when they are added. You can also sort them in ascending order. + +To sort files in descending order by the date when they are added, set **order** to **FileKey.DATE_ADDED + " DESC"**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.IMAGE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +### Querying Media Assets with the Specified Album Name + +The following describes how to query media assets in **myAlbum**. + +To specify the album name as the retrieval condition, set **selections** to **FileKey.ALBUM_NAME**. + +To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.IMAGE + let option = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs: ['myAlbum'], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +## Obtaining Images and Videos in an Album + +You can obtain media assets in an album in either of the following ways: + +- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name). +- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +**How to Develop** + +The following describes how to obtain videos in an album named **New Album 1**. + +1. Create a retrieval condition for obtaining the target **Album** instance. + + ```ts + let fileKeyObj = mediaLibrary.FileKey; + let AlbumNoArgsFetchOp = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'] + } + ``` + +2. Create a retrieval condition for obtaining videos in the target album. + + ```ts + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.VIDEO; + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + } + ``` + +3. Call **Album.getFileAssets** to obtain the videos in the target album. + +Complete sample code: + +```ts +async function getCameraImagePromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + } + let AlbumNoArgsFetchOp = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'] + } + + let albumList = await media.getAlbums(AlbumNoArgsFetchOp); + if (albumList.length > 0) { + const album = albumList[0]; + let fetchFileResult = await album.getFileAssets(imagesFetchOp); + let count = fetchFileResult.getCount(); + console.info("get mediaLibrary IMAGE number", count); + } else { + console.info('getAlbum list is: 0'); + } +} +``` + +## Obtaining the Thumbnail of an Image or a Video + +You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#getthumbnail8-2) with the thumbnail size passed in to obtain the thumbnail of an image or a video. Thumbnails are usually displayed on the UI. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +### Obtaining the Thumbnail of an Image + +Your application may need to obtain the thumbnail of an image for preview purposes. + +The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album. + +**How to Develop** + +1. Create a retrieval condition for obtaining images in the target album. +2. Call **getFileAssets** to obtain the images in the target album. +3. Call **getFirstObject** to obtain the first image among all the images obtained. +4. Call **getThumbnail** to obtain the thumbnail of the first image. + +```ts +async function getFirstThumbnailPromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + } + + let size = { width: 720, height: 720 }; + const fetchFileResult = await media.getFileAssets(imagesFetchOp); + if (fetchFileResult != undefined) { + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail(size).then((pixelMap) => { + pixelMap.getImageInfo().then((info) => { + console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); + }).catch((err) => { + console.info("getImageInfo failed with error:" + err); + }); + }).catch((err) => { + console.info("getImageInfo failed with error:" + err); + }); + } else { + console.info("get image failed with error"); + } +} +``` + +## Creating a Media Asset + +You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1) to create a media asset. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. +- [Obtain the public directory](medialibrary-filepath-guidelines.md). + +The following describes how to create a file of the **MediaType.FILE** type. + +```ts +async function example() { + let mediaType = mediaLibrary.MediaType.FILE; + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_DOCUMENTS); + media.createAsset(mediaType, "testFile.text", path).then ((asset) => { + console.info("createAsset successfully:"+ JSON.stringify(asset)); + }).catch((err) => { + console.info("createAsset failed with error:"+ err); + }); +} +``` + +## Moving a Media Asset to the Recycle Bin + +You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin. + +By default, files in the recycle bin will be stored for 30 days. During this period, you can set **isTrash** in **trash** to **false** to recover the files from the recycle bin. Application users can also recover the files through the system applications **Files** or **Gallery**. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to move the first file in the result set to the recycle bin. + +**How to Develop** + +1. Create a retrieval condition for obtaining images in the target album. +2. Call **getFileAssets** to obtain the images in the target album. +3. Call **getFirstObject** to obtain the first image among all the images obtained. +4. Call **trash** to move the first image to the recycle bin. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.FILE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset == undefined) { + console.error('asset not exist') + return + } + // Void callback. + asset.trash(true).then(() => { + console.info("trash successfully"); + }).catch((err) => { + console.info("trash failed with error:"+ err); + }); +} +``` + +## Renaming a Media Asset + +Renaming modifies the **FileAsset.displayName** attribute of a file, that is, the displayed file name, including the file name extension. + +After the modification, call [FileAsset.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-1) to commit the modification to the database. + +Before renaming a file, you must call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7) to obtain the file. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to rename the first file in the result set as **newtitle.text**. + +**How to Develop** + +1. Create a retrieval condition for obtaining images in the target album. +2. Call **getFileAssets** to obtain the images in the target album. +3. Call **getFirstObject** to obtain the first image among all the images obtained. +4. Rename the image as **newImage.jpg**. +5. Call **FileAsset.commitModify** to commit the modification of the attributes to the database. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.FILE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset == undefined) { + console.error('asset not exist') + return + } + asset.displayName = 'newImage.jpg'; + // Void callback. + asset.commitModify((err) => { + if (err) { + console.error('fileRename Failed '); + return; + } + console.log('fileRename successful.'); + }) +} +``` diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 4c293fdee7114866ebd969151c0914d29a144941..62bf66fd7cabb7e30c765126ddacba639bd951f5 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -9,15 +9,15 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | -| ohos.i18n | getSystemRegion(): string | Obtains the system region. | -| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | -| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | -| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | -| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | +| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | +| ohos.i18n | getSystemRegion(): string | Obtains the system region. | +| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | +| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | +| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | +| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | +| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | ### How to Develop @@ -26,7 +26,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). - + ```js var language = i18n.getSystemLanguage(); ``` @@ -42,7 +42,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Obtain the system locale. Call the **getSystemLocale** method to obtain the system locale. - + ```js var locale = i18n.getSystemLocale(); ``` @@ -51,7 +51,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **isRTL** method to check whether the locale's language is RTL. - + ```js var rtl = i18n.isRTL("zh-CN"); ``` @@ -67,7 +67,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Obtain the localized display of a language. Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var language = "en"; var locale = "zh-CN"; @@ -78,7 +78,7 @@ You can use APIs provided in the following table to obtain the system language a 7. Obtain the localized display of a country. Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var country = "US"; var locale = "zh-CN"; @@ -116,7 +116,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - + ```js var calendar = i18n.getCalendar("zh-CN", "gregory"); ``` @@ -135,7 +135,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Set the year, month, day, hour, minute, and second for the **Calendar** object. Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` @@ -144,7 +144,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. - + ```js calendar.setTimeZone("Asia/Shanghai"); var timezone = calendar.getTimeZone(); @@ -163,7 +163,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Set and obtain the minimum count of days in the first week for the **Calendar** object. Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - + ```js calendar.setMinimalDaysInFirstWeek(3); var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); @@ -173,7 +173,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. - + ```js var localizedName = calendar.getDisplayName("zh-CN"); ``` @@ -196,11 +196,11 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | -| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | -| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | +| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | +| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | +| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | ### How to Develop @@ -209,7 +209,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. - + ```js var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); ``` @@ -223,7 +223,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Format a phone number. Call the **format** method of **PhoneNumberFormat** to format the input phone number. - + ```js var formattedNumber = phoneNumberFormat.format("15812341234"); ``` @@ -236,15 +236,15 @@ The **unitConvert** API is provided to help you implement measurement conversion ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | +| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | ### How to Develop 1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert8) method to convert a measurement unit and format the display result. + Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result. ```js @@ -254,7 +254,7 @@ The **unitConvert** API is provided to help you implement measurement conversion var locale = "en-US"; var style = "long"; i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); - ``` + ``` ## Alphabet Index @@ -278,7 +278,7 @@ The **unitConvert** API is provided to help you implement measurement conversion Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - + ```js var indexUtil = i18n.getInstance("zh-CN"); ``` @@ -294,7 +294,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 3. Add an index. Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - + ```js indexUtil.addLocale("ar") ``` @@ -302,7 +302,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 4. Obtain the index of a string. Call the **getIndex** method to obtain the alphabet index of a string. - + ```js var text = "access index"; indexUtil.getIndex(text); @@ -336,7 +336,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **getLineInstance** method to instantiate a **BreakIterator** object. - + ```js var locale = "en-US" var breakIterator = i18n.getLineInstance(locale); @@ -357,7 +357,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. - + ```js var pos = breakIterator.current(); ``` @@ -383,7 +383,9 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. - + ```js var isboundary = breakIterator.isBoundary(5); ``` + + ``` \ No newline at end of file diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 424320dcc17f3dc0eb6d3e30970869da83874408..540e8dbf89029df9daa4825c5883eb7d41271412 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -13,13 +13,13 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | -| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | -| ohos.intl | toString(): string | Converts locale information into a string. | -| ohos.intl | maximize(): Locale | Maximizes locale information. | -| ohos.intl | minimize(): Locale | Minimizes locale information. | +| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | +| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | +| ohos.intl | toString(): string | Converts locale information into a string. | +| ohos.intl | maximize(): Locale | Maximizes locale information. | +| ohos.intl | minimize(): Locale | Minimizes locale information. | ### How to Develop @@ -81,13 +81,13 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to f ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | ### How to Develop @@ -144,12 +144,12 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to forma ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | +| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | +| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | ### How to Develop @@ -195,12 +195,12 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **Collator** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | -| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | +| ohos.intl | constructor()8+ | Creates a **Collator** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | +| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | +| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | ### How to Develop @@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings var collator = new intl.Collator(); ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). ```js var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); @@ -246,11 +246,11 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | -| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | +| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | +| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | ### How to Develop @@ -264,7 +264,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ var pluralRules = new intl.PluralRules(); ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). ```js var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); @@ -287,13 +287,13 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | ### How to Develop @@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) var relativeTimeFormat = new intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). ```js var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); diff --git a/en/application-dev/media/image.md b/en/application-dev/media/image.md index 8e6eca83375ea64b2948325fc1f7bf7f28746767..f3bb5fc9b59c8b290692e877033e78a5d9d4edef 100644 --- a/en/application-dev/media/image.md +++ b/en/application-dev/media/image.md @@ -21,45 +21,43 @@ let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { // Create a PixelMap object. const color = new ArrayBuffer(96); let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } - image.createPixelMap(color, opts, pixelmap => { - expect(pixelmap !== null).assertTrue(); - console.info('TC_001-1 success'); - done(); - }) +image.createPixelMap(color, opts, pixelmap => { + console.log('Succeeded in creating pixelmap.'); +}) + // Read pixels. pixelmap.readPixels(area,(data) => { - if(data !== null) { - var bufferArr = new Uint8Array(area.pixels); + 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; - } - } + console.info(' buffer ' + bufferArr[i]); + if(res) { + if(bufferArr[i] == 0) { + res = false; + console.log('readPixels end.'); + break; } + } + } + } +}) // Store pixels. const readBuffer = new ArrayBuffer(96); 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; + 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.log('readPixelsToBuffer end.'); + break; + } } } -} +}) // Write pixels. pixelmap.writePixels(area,() => { @@ -71,56 +69,51 @@ pixelmap.writePixels(area,() => { if(res) { if (readArr[i] !== 0) { res = false; - console.info('TC_022-1 Success'); - expect(true).assertTrue(); - done(); + console.log('readPixels end.please check buffer'); break; } } } + }) +}) // Write pixels to the buffer. pixelmap.writeBufferToPixels(writeColor).then(() => { const readBuffer = new ArrayBuffer(96); 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] !== i) { - res = false; - console.info('TC_023 Success'); - expect(true).assertTrue() - done(); + var bufferArr = new Uint8Array(readBuffer); + var res = true; + for (var i = 0; i < bufferArr.length; i++) { + if(res) { + if (bufferArr[i] !== i) { + res = false; + console.log('readPixels end.please check buffer'); break; } } } + }) +}) // Obtain image information. 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 == 4).assertTrue(); - done(); + console.log('Succeeded in getting imageInfo'); } }) // Release the PixelMap object. pixelmap.release(()=>{ - expect(true).assertTrue(); - console.log('TC_027-1 suc'); - done(); + console.log('Succeeded in releasing pixelmap'); }) -let path = '/data/local/tmp/test.jpg'; // Create an image source (uri). -const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg' +let path = '/data/local/tmp/test.jpg'; +const imageSourceApi = image.createImageSource(path); // Create an image source (fd). -const imageSourceApi = image.createImageSource(29); +let fd = 29; +const imageSourceApi = image.createImageSource(fd); // Create an image source (data). const data = new ArrayBuffer(96); @@ -128,15 +121,15 @@ const imageSourceApi = image.createImageSource(data); // Release the image source. imageSourceApi.release(() => { - console.info('TC_044-1 Success'); - }) + console.log('Succeeded in releasing imagesource'); +}) // Encode the image. const imagePackerApi = image.createImagePacker(); +const imageSourceApi = image.createImageSource(0); +let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, data => { - console.info('TC_062-1 finished'); - expect(data !== null).assertTrue(); - done(); + console.log('Succeeded in packing'); }) // Release the ImagePacker object. @@ -164,59 +157,40 @@ let decodingOptions = { // Create a pixel map in callback mode. imageSourceApi.createPixelMap(decodingOptions, pixelmap => { - console.info('TC_050 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) -} + console.log('Succeeded in creating pixelmap.'); +}) // Create a pixel map in promise mode. imageSourceApi.createPixelMap().then(pixelmap => { - console.info('TC_050-11 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); + console.log('Succeeded in creating pixelmap.'); }) // Capture error information when an exception occurs during function invoking. catch(error => { - console.log('TC_050-11 error: ' + error); - expect().assertFail(); - done(); + console.log('Failed in creating pixelmap.' + error); }) // Obtain the number of bytes in each line of pixels. pixelmap.getBytesNumberPerRow( num => { - console.info('TC_025-1 num is ' + num); - expect(num == expectNum).assertTrue(); - done(); + console.log('Succeeded in getting BytesNumber PerRow.'); }) // Obtain the total number of pixel bytes. pixelmap.getPixelBytesNumber(num => { - console.info('TC_026-1 num is ' + num); - expect(num == expectNum).assertTrue(); - done(); + console.log('Succeeded in getting PixelBytesNumber.'); }) // Obtain the pixel map information. pixelmap.getImageInfo( imageInfo => {}) - -// Print the failure information. -console.info('TC_024-1 imageInfo is empty'); -expect(false).assertTrue() // Release the PixelMap object. pixelmap.release(()=>{ - expect(true).assertTrue(); - console.log('TC_027-1 suc'); - done(); + console.log('Succeeded in releasing pixelmap'); }) // Capture release failure information. catch(error => { - console.log('TC_027-1 error: ' + error); - expect().assertFail(); - done(); + console.log('Failed in releasing pixelmap.' + error); }) ``` @@ -230,9 +204,7 @@ const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.p // Print the error message if the image source fails to be created. if (imageSourceApi == null) { - console.info('TC_062 create image source failed'); - expect(false).assertTrue(); - done(); + console.log('Failed in creating imageSource.'); } // Create an image packer if the image source is successfully created. @@ -240,9 +212,7 @@ const imagePackerApi = image.createImagePacker(); // Print the error information if the image packer fails to be created. if (imagePackerApi == null) { - console.info('TC_062 create image packer failed'); - expect(false).assertTrue(); - done(); + console.log('Failed in creating imagePacker.'); } // Set encoding parameters if the image packer is successfully created. @@ -252,19 +222,15 @@ let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg. // Encode the image. imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { - console.info('TC_062 finished'); - expect(data !== null).assertTrue(); - done(); + console.log('Succeeded in packing'); }) - + // Release the image packer after the encoding is complete. imagePackerApi.release(); // Obtain the image source information. imageSourceApi.getImageInfo(imageInfo => { - console.info('TC_045 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); + console.log('Succeeded in getting imageInfo'); }) // Update incremental data. diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 280efd8afa5fa845dab0d607ed94b33e2a75e6d3..bf16d91435bf68ebd6f93a1a52b5f6da35e67169 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -4,5 +4,6 @@ - [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) - [Native Window Development](native-window-guidelines.md) +- [Using MindSpore Lite for Model Inference](native-window-guidelines.md) diff --git a/en/application-dev/napi/figures/01.png b/en/application-dev/napi/figures/01.png new file mode 100644 index 0000000000000000000000000000000000000000..5293e5afe5a8637dbef3fd0b32c7bd43d60e4368 Binary files /dev/null and b/en/application-dev/napi/figures/01.png differ diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..47ede475575484d60317e9ed7e2afe586fb12524 --- /dev/null +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -0,0 +1,216 @@ +# Using MindSpore Lite for Model Inference + +## When to Use + +MindSpore Lite is an AI engine that provides AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition. + +This document describes the general development process for MindSpore Lite model inference. + +## Basic Concepts + +Before getting started, you need to understand the following basic concepts: + +**Tensor**: a special data structure that is similar to arrays and matrices. It is a basic data structure used in MindSpore Lite network operations. + +**Float16 inference**: a mode in which Float16 is used for inference. Float16, also called half-precision, uses 16 bits to represent a number. + + + +## Available APIs +APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. +### Context APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| +|void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| +|OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| +|void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| +|void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| +|void OH_AI_ContextAddDeviceInfo(OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info)|Adds a runtime device information object.| + +### Model APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ModelHandle OH_AI_ModelCreate()|Creates a model object.| +|OH_AI_Status OH_AI_ModelBuildFromFile(OH_AI_ModelHandle model, const char *model_path,OH_AI_ModelType odel_type, const OH_AI_ContextHandle model_context)|Loads and builds a MindSpore model from a model file.| +|void OH_AI_ModelDestroy(OH_AI_ModelHandle *model)|Destroys a model object.| + +### Tensor APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_TensorHandleArray OH_AI_ModelGetInputs(const OH_AI_ModelHandle model)|Obtains the input tensor array structure of a model.| +|int64_t OH_AI_TensorGetElementNum(const OH_AI_TensorHandle tensor)|Obtains the number of tensor elements.| +|const char *OH_AI_TensorGetName(const OH_AI_TensorHandle tensor)|Obtains the name of a tensor.| +|OH_AI_DataType OH_AI_TensorGetDataType(const OH_AI_TensorHandle tensor)|Obtains the tensor data type.| +|void *OH_AI_TensorGetMutableData(const OH_AI_TensorHandle tensor)|Obtains the pointer to variable tensor data.| + +## How to Develop +The following figure shows the development process for MindSpore Lite model inference. + +**Figure 1** Development process for MindSpore Lite model inference +![how-to-use-mindspore-lite](figures/01.png) + +The development process consists of the following main steps: + +1. Prepare the required model. + + The required model can be downloaded directly or obtained using the model conversion tool. + + - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example. + - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format. + +2. Create a context, and set parameters such as the number of runtime threads and device type. + + ```c + // Create a context, and set the number of runtime threads to 2 and the thread affinity mode to 1 (big cores first). + OH_AI_ContextHandle context = OH_AI_ContextCreate(); + if (context == NULL) { + printf("OH_AI_ContextCreate failed.\n"); + return OH_AI_STATUS_LITE_ERROR; + } + const int thread_num = 2; + OH_AI_ContextSetThreadNum(context, thread_num); + OH_AI_ContextSetThreadAffinityMode(context, 1); + // Set the device type to CPU, and disable Float16 inference. + OH_AI_DeviceInfoHandle cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU); + if (cpu_device_info == NULL) { + printf("OH_AI_DeviceInfoCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + OH_AI_DeviceInfoSetEnableFP16(cpu_device_info, false); + OH_AI_ContextAddDeviceInfo(context, cpu_device_info); + ``` + +3. Create, load, and build the model. + + Call **OH_AI_ModelBuildFromFile** to load and build the model. + + In this example, the **argv[1]** parameter passed to **OH_AI_ModelBuildFromFile** indicates the specified model file path. + + ```c + // Create a model. + OH_AI_ModelHandle model = OH_AI_ModelCreate(); + if (model == NULL) { + printf("OH_AI_ModelCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + + // Load and build the model. The model type is OH_AI_ModelTypeMindIR. + int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_ModelTypeMindIR, context); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelBuildFromFile failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +4. Input data. + + Before executing model inference, you need to populate data to the input tensor. In this example, random data is used to populate the model. + + ```c + // Obtain the input tensor. + OH_AI_TensorHandleArray inputs = OH_AI_ModelGetInputs(model); + if (inputs.handle_list == NULL) { + printf("OH_AI_ModelGetInputs failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + // Use random data to populate the tensor. + ret = GenerateInputDataWithRandom(inputs); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("GenerateInputDataWithRandom failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +5. Execute model inference. + + Call **OH_AI_ModelPredict** to perform model inference. + + ```c + // Execute model inference. + OH_AI_TensorHandleArray outputs; + ret = OH_AI_ModelPredict(model, inputs, &outputs, NULL, NULL); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelPredict failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +6. Obtain the output. + + After model inference is complete, you can obtain the inference result through the output tensor. + + ```c + // Obtain the output tensor and print the information. + for (size_t i = 0; i < outputs.handle_num; ++i) { + OH_AI_TensorHandle tensor = outputs.handle_list[i]; + int64_t element_num = OH_AI_TensorGetElementNum(tensor); + printf("Tensor name: %s, tensor size is %zu ,elements num: %lld.\n", OH_AI_TensorGetName(tensor), + OH_AI_TensorGetDataSize(tensor), element_num); + const float *data = (const float *)OH_AI_TensorGetData(tensor); + printf("output data is:\n"); + const int max_print_num = 50; + for (int j = 0; j < element_num && j <= max_print_num; ++j) { + printf("%f ", data[j]); + } + printf("\n"); + } + ``` + +7. Destroy the model. + + If the MindSpore Lite inference framework is no longer needed, you need to destroy the created model. + + ```c + // Destroy the model. + OH_AI_ModelDestroy(&model); + ``` + +## Verification + +1. Compile **CMakeLists.txt**. + + ```cmake + cmake_minimum_required(VERSION 3.14) + project(Demo) + + add_executable(demo main.c) + + target_link_libraries( + demo + mindspore-lite.huawei + pthread + dl + ) + ``` + - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.cmake"`. + + - The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`. + +2. Run the CMake tool. + + - Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board. + - Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command: + + ```shell + ./demo mobilenetv2.ms + ``` + + The inference is successful if the output is similar to the following: + + ```shell + # ./QuickStart ./mobilenetv2.ms + Tensor name: Softmax-65, tensor size is 4004 ,elements num: 1001. + output data is: + 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 + ``` diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index f471f4a6eed7d3eb2c96dab8cae4cb7480a13616..188b4f1336e2c56562f594e42dc26cabf8a8fc55 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -17,11 +17,11 @@ You can `import` the native .so that contains the JS processing logic. For examp ### .so Naming Rules -Each module has a .so file. For example, if the module name is `hello`, name the .so file **libhello.so**. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. +Each module has a .so file. For example, if the module name is `hello`, name the .so file `libhello.so`. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. ### JS Objects and Threads -The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. +The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. Observe the following rules: * The NAPIs can be used only in JS threads. * **env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread. @@ -640,8 +640,3 @@ export default { } } ``` -## Samples -The following samples are provided for native API development: -- [`NativeAPI`: NativeAPI (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) -- [First Native C++ Application (eTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) -- [Native Component (eTS) (API9) ](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) diff --git a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md index 1894942945c53a4d36bc2f9c892de28359faa9ff..b789e20218f1d8508ce5dbf1b515179e6f23b9ef 100644 --- a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md +++ b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md @@ -37,9 +37,7 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind import reminderAgent from '@ohos.reminderAgent'; import notification from '@ohos.notification'; export default { - // For a JS project: - // timer: { - // For an eTS project: + // eTS project: let timer : reminderAgent.ReminderRequestTimer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10, @@ -69,9 +67,7 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind Sample code for defining a reminder agent for a calendar event: ```js - // For a JS project: - // calendar: { - // For an eTS project: + // eTS project: let calendar : reminderAgent.ReminderRequestCalendar = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, dateTime: { @@ -117,9 +113,7 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind Sample code for defining a reminder agent for an alarm: ```js - // For a JS project: - // alarm: { - // For an eTS project: + // eTS project: let alarm : reminderAgent.ReminderRequestAlarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 11, @@ -171,4 +165,3 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind ``` - diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index d5a6d7bdfbc6dcdd5b94d36e155d4650fc70630c..dfb611ea572b80486756faaa4b004513cd6858a7 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -13,14 +13,14 @@ Each application can subscribe to common events as required. After your applicat ## Common Event Subscription Development ### When to Use -You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md). +You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#support). ### Available APIs | API | Description| | ---------------------------------------------------------------------------------------------- | ----------- | -| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| -| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | -| commonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| +| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| +| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | +| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| ### How to Develop 1. Import the **commonEvent** module. @@ -32,7 +32,8 @@ import commonEvent from '@ohos.commonEvent'; 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). ```js -private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Used to save the created subscriber object for subsequent subscription and unsubscription. +private subscriber = null // Subscriber information var subscribeInfo = { @@ -82,8 +83,8 @@ You can use the **publish** APIs to publish a custom common event, which can car ### Available APIs | API | Description| | ---------------------------------- | ------ | -| commonEvent.publish(event: string, callback: AsyncCallback) | Publishes a common event.| -| commonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| +| publish(event: string, callback: AsyncCallback) | Publishes a common event.| +| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| ### How to Develop #### Development for Publishing a Common Event @@ -119,7 +120,7 @@ import commonEvent from '@ohos.commonEvent' // Attributes of a common event. var options = { code: 1, // Result code of the common event - data: "initial data",// Result data of the common event + data: "initial data";// Result data of the common event } ``` @@ -144,7 +145,7 @@ You can use the **unsubscribe** API to unsubscribe from a common event. ### Available APIs | API | Description| | ---------------------------------- | ------ | -| commonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| +| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| ### How to Develop 1. Import the **commonEvent** module. @@ -153,7 +154,7 @@ You can use the **unsubscribe** API to unsubscribe from a common event. import commonEvent from '@ohos.commonEvent'; ``` -2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development). +2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#common-event-subscription-development). 3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. ```js diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md index 8be39b2cc823398e4572a77469909f9fd06e2a5f..75237412fdf29d88843a9f23fa653f64f2de7c86 100644 --- a/en/application-dev/notification/notification-brief.md +++ b/en/application-dev/notification/notification-brief.md @@ -1,22 +1,19 @@ # Common Event and Notification Overview -The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, or warning information. +The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more. Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. ![ces](figures/ces.png) - System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events. - - Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications. - The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: +The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: - - Display received SMS messages and instant messages. - - - Display push messages of applications, such as advertisements, version updates, and news notifications. - - - Display ongoing events, such as music playback, navigation information, and download progress. +- Display received SMS messages and instant messages. +- Display push messages of applications, such as advertisements, version updates, and news notifications. +- Display ongoing events, such as music playback, navigation information, and download progress. Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions. diff --git a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md index 9baaba331069e20f35abb254d9761549b9c6f33e..71cc213f3ba56b31af7c5f1b4dc7bc9bb924b1fd 100644 --- a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md +++ b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @@ -2,18 +2,15 @@ -HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop, distributed platform developed based on the IntelliJ IDEA Community (Open Source) Edition. It helps you develop versatile all-device, all-scenario applications, offering distributed multi-device development, debugging, and simulation, as well as comprehensive quality and security safeguards. +HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop integrated development environment (IDE) powered by the IntelliJ IDEA Community Edition and oriented to OpenHarmony devices in all scenarios. It allows you to create project templates, and develop, build, debug, and release OpenHarmony applications from end to end. -[DevEco Studio 3.0 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) stands out in the following aspects: +[DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/) stands out in the following aspects: -- One-stop information acquisition platform -- A wide range of device project templates -- Efficient code editing -- Visualized UI development -- Bidirectional and instant UI preview -- High-performing compilation tool Hvigor -- Support for application development based on the device System Capability (SysCap) sets -- Automatic application signing mechanism -- A diverse array of code debugging and profiling features +- **Efficient and intelligent code editing**: Code highlighting, intelligent code completion, code error check, automatic code navigation, code formatting, and code search for programming languages such as ArkTS, JavaScript, and C/C++. For details, see [Editor Usage Tips](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-editor-usage-tips-0000001263360493). +- **Low-code development**: A diverse array of features to punch up your UI development productivity, including component drag and drop, visualized data binding, instant previewing, and low-code development for service widgets. For details, see [Using Low-Code Development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652). +- **Multi-device bidirectional real-time preview**: Bidirectional preview, real-time preview, live preview, component preview, and multi-device preview of UI code to quickly view how your code runs on devices. For details, see [Previewing Your App/Service](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596). +- **High-performance build system**: Hvigor, a compilation and building tool to compile and package applications/services in one-click mode, better supporting ArkTS/JS development. +- **One-stop information acquisition**: A one-stop information acquisition platform that takes into account the developer journey of learning, development, and help seeking, in order to facilitate developer activities. +- **Efficient code debugging**: Various debugging capabilities such as TS, JS, and C/C++ code breakpoint setting, single-step execution, and variable viewing, improving the efficiency of analyzing application/service issues. -For more information, see [HUAWEI DevEco Studio For OpenHarmony User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). +For more information, see [DevEco Studio (OpenHarmony) User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). diff --git a/en/application-dev/quick-start/package-structure.md b/en/application-dev/quick-start/package-structure.md index 076bc9474ba724746938c1a4da837a3679c73d5a..6c1ecfe7be836e8b17dcb7d6d1045354d5aa386d 100644 --- a/en/application-dev/quick-start/package-structure.md +++ b/en/application-dev/quick-start/package-structure.md @@ -2,19 +2,19 @@ # Application Package Structure Configuration File -In an application development project, you need to declare the package structure of the application in the **config.json** file. +When developing an application in the Feature Ability (FA) model, you must declare the package structure of the application in the **config.json** file. ## Internal Structure of the config.json File -The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. See Table 1 for details. +The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. For details, see Table 1. Table 1 Internal structure of the config.json file | Tag | Description | Data Type| Initial Value Allowed| | ------------ | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of an application. Different HAP files of the same application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| deviceConfig | Application configuration applied to a specific type of device. For details, see [Internal Structure of the deviceconfig Tag](#internal-structure-of-the-deviceconfig-tag).| Object | No | -| module | Configuration of a HAP file. The **module** configuration is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | +| app | Global configuration of the application. Different HAP files of the same application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | +| deviceConfig | Application configuration applied to a specific type of device. For details, see [Internal Structure of the deviceconfig Tag](#internal-structure-of-the-deviceconfig-tag).| Object | No | +| module | Configuration of a HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | Example of the **config.json** file: @@ -86,12 +86,15 @@ The **app** tag contains the global configuration information of the application Table 2 Internal structure of the app tag -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| bundleName | Bundle name of the application. It uniquely identifies the application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The value is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String | No | -| vendor | Description of the application vendor. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| version | Version information of the application. For details, see Table 3. | Object | No | -| apiVersion | OpenHarmony API version on which the application depends. For details, see Table 4. | Object | Yes (initial value: left empty)| +| Attribute | Description | Data Type| Initial Value Allowed | +| ----------------- | ------------------------------------------------------------ | -------- | --------------------------- | +| bundleName | Bundle name, which uniquely identifies an application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The value is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String | No | +| vendor | Description of the application vendor. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | +| version | Version of the application. For details, see Table 3. | Object | No | +| apiVersion | OpenHarmony API version on which the application depends. For details, see Table 4. | Object | Yes (initial value: left empty) | +| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8.| Boolean | Yes (initial value: **false**)| +| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8. | Boolean | Yes (initial value: **true**) | +| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | Table 3 Internal structure of version @@ -99,7 +102,7 @@ Table 3 Internal structure of version | ------------------------ | ------------------------------------------------------------ | -------- | -------------------------- | | name | Application version number visible to users. The value can be customized and cannot exceed 127 bytes. The customization rules are as follows:
API 5 and earlier versions: A three-segment version number is recommended, for example, A.B.C (also compatible with A.B). In the version number, A, B, and C are integers ranging from 0 to 999. Other formats are not supported.
A indicates the major version number.
B indicates the minor version number.
C indicates the patch version number.
API 6 and later versions: A four-segment version number is recommended, for example, A.B.C.D. In the version number, A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
A indicates the major version number.
B indicates the minor version number.
C indicates the feature version number.
D indicates the patch version number.| Number | No | | code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The value rules are as follows:
API 5 and earlier versions: It is a non-negative integer less than 32 bits in binary mode, converted from the value of version.name as follows: The conversion rules are as follows:
Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001.
API 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer ranging from 2 to 31. Note that the value must be updated each time the application version is updated. The value for a later version must be greater than that for an earlier version.| Number | No | -| minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with the version on other devices in the cross-device scenario.
The value rules are the same as those of **version.code**.| Number | No (initial value: **code** attribute value)| +| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices.
The value rules are the same as those of **version.code**.| Number | No (initial value: **code** attribute value)| Table 4 Internal structure of apiVersion @@ -116,15 +119,15 @@ Example of the app tag structure: "bundleName": "com.example.myapplication", "vendor": "example", "version": { - "code": 1, - "name": "1.0" + "code": 1, + "name": "1.0" }, "apiVersion": { - "compatible": 4, - "target": 5, - "releaseType": "Beta1" + "compatible": 4, + "target": 5, + "releaseType": "Beta1" } - } +} ``` ### Internal Structure of the deviceConfig Tag @@ -133,13 +136,13 @@ The **deviceConfig** tag contains the application configuration information on t Table 5 Internal structure of the deviceConfig tag -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------ | ----------------------------------------------- | -------- | ------------------ | -| default | Application configuration applied to all types of devices. See Table 6. | Object | No | -| tablet | Application configuration specific to tablets. See Table 6. | Object | Yes (initial value: left empty)| -| tv | Application configuration specific to smart TVs. See Table 6. | Object | Yes (initial value: left empty)| -| car | Application configuration specific to head units. See Table 6. | Object | Yes (initial value: left empty)| -| wearable | Application configuration specific to wearables. See Table 6. | Object | Yes (initial value: left empty)| +| Attribute| Description | Data Type| Initial Value Allowed | +| -------- | ----------------------------------------- | -------- | ------------------ | +| default | Application configuration applied to all types of devices. For details, see Table 6.| Object | No | +| tablet | Application configuration specific to tablets. For details, see Table 6. | Object | Yes (initial value: left empty)| +| tv | Application configuration specific to smart TVs. For details, see Table 6. | Object | Yes (initial value: left empty)| +| car | Application configuration specific to head units. For details, see Table 6. | Object | Yes (initial value: left empty)| +| wearable | Application configuration specific to wearables. For details, see Table 6.| Object | Yes (initial value: left empty)| For details about the internal structures of device attributes, see Table 6. @@ -147,12 +150,13 @@ Table 6 Internal structure of device attributes | Attribute | Description | Data Type| Initial Value Allowed | | ------------------ | ------------------------------------------------------------ | -------- | ----------------------- | -| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. The value can contain a maximum of 31 characters.| String | Yes | +| process | Process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. The value can contain a maximum of 31 characters.| String | Yes | +| keepAlive | Whether the application is always kept alive. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | | supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**)| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **true**) | | directLaunch | Whether the application can be started when the device is locked. The value **true** means that the application can be started when the device is locked. Devices running OpenHarmony do not support this attribute.| Boolean | Yes (initial value: **false**)| -| ark | Maple configuration. See Table 7. | Object | Yes (initial value: left empty) | -| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code. See Table 9.| Object | Yes (initial value: left empty) | +| ark | Maple configuration. For details, see Table 7. | Object | Yes (initial value: left empty) | +| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code. For details, see Table 9.| Object | Yes (initial value: left empty) | Table 7 Internal structure of the ark attribute @@ -179,32 +183,32 @@ Table 10 Internal structure of the securityConfig attribute | Attribute | Sub-attribute | Description | Data Type| Initial Value Allowed | | -------------- | ------------------ | ------------------------------------------------------------ | -------- | ---------------- | -| domainSettings | - | Security settings of the custom network domain. This attribute allows nested domains. To be more specific, the **domainSettings** object of a large domain can be nested with the **domainSettings** objects of small network domains.| Object| Yes (initial value: left empty)| -| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute.
**true**: Plaintext traffic can be transmitted.
**false**: Plaintext traffic cannot be transmitted.| Boolean| No | -| | domains | Domain name configuration. This attribute consists of the **subdomains** and **name** sub-attributes.
**subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches.
**name** (string): indicates the domain name.| Object array| No | +| domainSettings | - | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| +| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute.
**true**: Plaintext traffic can be transmitted.
**false**: Plaintext traffic cannot be transmitted.| Boolean| No | +| | domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**.
**subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches.
**name** (string): indicates the domain name.| Object array| No | Example of the deviceConfig tag structure: ```json "deviceConfig": { - "default": { - "process": "com.example.test.example", - "supportBackup": false, - "network": { - "cleartextTraffic": true, - "securityConfig": { - "domainSettings": { - "cleartextPermitted": true, - "domains": [ - { - "subdomains": true, - "name": "example.ohos.com" - } - ] - } - } - } - } + "default": { + "process": "com.example.test.example", + "supportBackup": false, + "network": { + "cleartextTraffic": true, + "securityConfig": { + "domainSettings": { + "cleartextPermitted": true, + "domains": [ + { + "subdomains": true, + "name": "example.ohos.com" + } + ] + } + } + } + } } ``` @@ -214,76 +218,78 @@ The **module** tag contains the configuration information of the HAP file. For d Table 11 Internal structure of the module tag -| Attribute | Description | Data Type | Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| String | No if any ability using the Page template exists | -| package | Structure name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | -| name | Class name of the HAP file. The value is in the reverse domain name notation. The prefix must be the same as the package name specified by the **package** label at the same level. The value can also start with a period (.). The value is a string with a maximum of 255 bytes.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | -| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| supportedModes | Mode supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty) | -| deviceType | Type of device on which the abilities can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No | -| distro | Distribution description of the current HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 12.| Object | No | -| metaData | Metadata of the HAP file. For details, see Table 13. | Object | Yes (initial value: left empty) | -| abilities | All abilities in the current module. The value is an array of objects, each of which represents a shortcut object. For details, see Table 17.| Object array | Yes (initial value: left empty) | -| js | A set of JS modules developed using the ArkUI framework. Each element in the set represents the information about a JS module. For details, see Table 22.| Object array | Yes (initial value: left empty) | -| shortcuts | Shortcut information of the application. The value is an array of objects, each of which represents a shortcut object. For details, see Table 25.| Object array | Yes (initial value: left empty) | -| reqPermissions | Permissions that the application applies for from the system before its running. For details, see Table 21. | Object array | Yes (initial value: left empty) | -| colorMode | Color mode of the application.
**dark**: Resources applicable for the dark mode are selected.
**light**: Resources applicable for the light mode are selected.
**auto**: Resources are selected based on the color mode of the system.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **auto**) | -| distroFilter | Application distribution rules.
AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29. | Object | Yes (initial value: left empty)
Set this attribute when an application has multiple entry modules. | -| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | -| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | -| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | +| Attribute | Description | Data Type | Initial Value Allowed | +| ----------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| String | No if any ability using the Page template exists | +| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | No | +| name | Class name of the HAP file. The value is in the reverse domain name notation, with the prefix same as the package name specified by **package** at the same level. It can also start with a period (.). The value is a string with a maximum of 255 bytes.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | +| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | +| supportedModes | Mode supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty) | +| deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No | +| distro | Distribution description of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 12.| Object | No | +| metaData | Metadata of the HAP file. For details, see Table 13. | Object | Yes (initial value: left empty) | +| abilities | All abilities in the current module. The value is an array of objects, each of which represents a shortcut object. For details, see Table 17.| Object array | Yes (initial value: left empty) | +| js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module. For details, see Table 22.| Object array | Yes (initial value: left empty) | +| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object. For details, see Table 25.| Object array | Yes (initial value: left empty) | +| reqPermissions | Permissions that the application requests from the system when it is running. For details, see Table 21. | Object array | Yes (initial value: left empty) | +| colorMode | Color mode of the application. Available values are as follows:
**"dark"**: Resources applicable for the dark mode are selected.
**"light"**: Resources applicable for the light mode are selected.
**"auto"**: Resources are selected based on the color mode of the system.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **auto**) | +| distroFilter | Distribution rules of the application.
AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29.| Object | Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| +| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | +| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | +| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | +| testRunner | Test runner configuration. For details, see Table 36. | Object | Yes (initial value: left empty) | +| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The caller of the application must have these permissions to properly call the app. For details, see Table 37.| Object | Yes (initial value: left empty) | Example of the **module** tag structure: ```json "module": { - "mainAbility": "MainAbility", - "package": "com.example.myapplication.entry", - "name": ".MyOHOSAbilityPackage", - "description": "$string:description_application", - "supportModes": [ - "drive" - ], - "deviceType": [ - "car" - ], - "distro": { - "moduleName": "ohos_entry", - "moduleType": "entry" - }, - "abilities": [ - ... - ], - "shortcuts": [ - ... - ], - "js": [ - ... - ], - "reqPermissions": [ - ... - ], - "colorMode": "light" + "mainAbility": "MainAbility", + "package": "com.example.myapplication.entry", + "name": ".MyOHOSAbilityPackage", + "description": "$string:description_application", + "supportModes": [ + "drive" + ], + "deviceType": [ + "car" + ], + "distro": { + "moduleName": "ohos_entry", + "moduleType": "entry" + }, + "abilities": [ + ... + ], + "shortcuts": [ + ... + ], + "js": [ + ... + ], + "reqPermissions": [ + ... + ], + "colorMode": "light" } ``` Table 12 Internal structure of the distro attribute -| Attribute | Description | Data Type| Initial Value Allowed| -| ---------------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -------- | ---------- | -| moduleName | Name of the current HAP file. The maximum length is 31 characters. | String | No | -| moduleType | Type of the current HAP file. The value can be **entry** or **feature**. For the HAR type, set this attribute to **har**. | String | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.
Pay attention to the following:
When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap **must be **true**.
When **entry.hap** is set to **false**, **feature.hap** related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| deliveryWithInstall | Whether the HAP file supports the installation with application.
**true**: The HAP file supports the installation with application.
**false**: The HAP file does not support the installation with application. | Boolean | No | +| Attribute | Description | Data Type| Initial Value Allowed| +| ---------------- | ------------------------------------------------------------ | -------- | ---------- | +| moduleName | Name of the HAP file. The maximum length is 31 characters. | String | No | +| moduleType | Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this attribute to **har**.| String | No | +| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.
Pay attention to the following:
- When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap **must be **true**.
- When **entry.hap** is set to **false**, **feature.hap** related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | +| deliveryWithInstall | Whether the HAP file is installed with application.
**true**: The HAP file is installed together with the application.
**false**: The HAP file is not installed together with the application.| Boolean| No| Example of the **distro** attribute structure: ```json "distro": { - "moduleName": "ohos_entry", - "moduleType": "entry", - "installationFree": true, + "moduleName": "ohos_entry", + "moduleType": "entry", + "installationFree": true, "deliveryWithInstall": true } ``` @@ -300,9 +306,9 @@ Table 14 Internal structure of the parameters attribute | Attribute | Description | Data Type| Initial Value Allowed | | ----------- | ------------------------------------------------------------ | -------- | ------------------ | -| description | Description of the parameter. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| -| name | Name of the parameter. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the parameter, for example, **Integer**. | String | No | +| description | Description of the parameter passed for calling the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| +| name | Name of the parameter passed for calling the ability. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| +| type | Type of the parameter passed for calling the ability, for example, **Integer**. | String | No | Table 15 Internal structure of the results attribute @@ -310,15 +316,15 @@ Table 15 Internal structure of the results attribute | ----------- | ------------------------------------------------------------ | -------- | -------------------- | | description | Description of the return value. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| | name | Name of the return value. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the return value, for example, **Integer**. | String | No | +| type | Type of the return value, for example, **Integer**. | String | No | Table 16 Internal structure of the customizeData attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ---------------------------------------------------------- | -------- | -------------------- | -| name | Key of a data element. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of a data element. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Custom format of the data element. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty)| +| name | Key of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| extra | Custom format of the data item. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty)| Example of the **metaData** attribute structure: @@ -347,19 +353,19 @@ Table 17 Internal structure of the abilities attribute | Attribute | Description | Data Type | Initial Value Allowed | | ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- | | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) | -| name | Name of the ability. The value is a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDE tools. The value can contain a maximum of 127 characters.| String | No | +| name | Ability name. The value can be a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 characters. | String | No | | description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | -| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String | Yes (initial value: left empty) | -| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | +| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. | String | Yes (initial value: left empty) | +| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty) | | uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 characters. | String | Yes (No for abilities using the Data template) | -| launchType | Startup type of the ability. The value can be **standard** or **singleton**.
**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton startup type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: **"singleton"**) | +| launchType | Launch type of the ability. Available values are as follows:
**"standard"**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**"singleton"**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton startup type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **"singleton"**) | | visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean | Yes (initial value: **false**) | -| permissions | Permissions required for abilities of another application to call the current ability, generally in the format of a reverse domain name. The value can be either the permissions predefined in the OS or your custom permissions.| String array| Yes (initial value: left empty) | +| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | | skills | Types of the **want** that can be accepted by the ability. | Object array | Yes (initial value: left empty) | | deviceCapability | Device capabilities required to run the ability.| String array| Yes (initial value: left empty) | | metaData | Metadata. For details, see Table 13. | Object | Yes (initial value: left empty) | -| type | Type of the ability. Available values are as follows:
**page**: FA developed using the Page template to provide the capability of interacting with users.
**service**: PA developed using the Service template to provide the capability of running tasks in the background.
**data**: PA developed using the Data template to provide unified data access for external systems.
**CA**: ability that can be started by other applications as a window.| String | No | -| orientation | Display orientation of the ability. This attribute applies only to the ability using the Page template. Available values are as follows:
unspecified: indicates that the system automatically determines the display orientation of the ability.
**landscape**: indicates the landscape orientation.
**portrait**: indicates the portrait orientation.
**followRecent**: indicates that the orientation follows the most recent application in the stack.| String | Yes (initial value: **"unspecified"**) | +| type | Ability type. Available values are as follows:
**"page"**: FA developed using the Page template to provide the capability of interacting with users.
**"service"**: PA developed using the Service template to provide the capability of running tasks in the background.
**"data"**: PA developed using the Data template to provide unified data access for external systems.
**"CA"**: ability that can be started by other applications as a window. | String | No | +| orientation | Display orientation of the ability. This attribute applies only to the ability using the Page template. Available values are as follows:
**"unspecified"**: indicates that the system automatically determines the display orientation of the ability.
**"landscape"**: indicates the landscape orientation.
**"portrait"**: indicates the portrait orientation.
**"followRecent"**: indicates that the orientation follows the most recent application in the stack. | String | Yes (initial value: **"unspecified"**) | | backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This attribute applies only to the ability using the Service template. Available values are as follows:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**pictureInPicture**: picture in picture (PiP) and small-window video playback services
**voip**: voice/video call and VoIP services
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services
**wifiInteraction**: WLAN scanning, connection, and transmission services
**screenFetch**: screen recording and screenshot services
**multiDeviceConnection**: multi-device interconnection service| String array| Yes (initial value: left empty) | | grantPermission | Whether permissions can be granted for any data in the ability. | Boolean | Yes (initial value: left empty) | | readPermission | Permission required for reading data in the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | @@ -367,15 +373,16 @@ Table 17 Internal structure of the abilities attribute | configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. Available values are as follows:
**mcc**: indicates that the mobile country code (MCC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MCC is updated.
**mnc**: indicates that the mobile network code (MNC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MNC is updated.
**locale**: indicates that the locale is changed. Typical scenario: The user has selected a new language for the text display of the device.
**layout**: indicates that the screen layout is changed. Typical scenario: Currently, different display forms are all in the active state.
**fontSize**: indicates that font size is changed. Typical scenario: A new global font size is set.
**orientation**: indicates that the screen orientation is changed. Typical scenario: The user rotates the device.
**density**: indicates that the display density is changed. Typical scenario: The user may specify different display ratios, or different display forms are active at the same time.
**size**: indicates that the size of the display window is changed.
**smallestSize**: indicates that the length of the shorter side of the display window is changed.
**colorMode**: indicates that the color mode is changed.| String array| Yes (initial value: left empty) | | mission | Task stack of the ability. This attribute applies only to the ability using the Page template. By default, all abilities in an application belong to the same task stack. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: bundle name of the application) | | targetAbility | Target ability that this ability alias points to. This attribute applies only to the ability using the Page template. If the **targetAbility** attribute is set, only **name**, **icon**, **label**, **visible**, **permissions**, and **skills** take effect in the current ability (ability alias). Other attributes use the values of the **targetAbility** attribute. The target ability must belong to the same application as the alias and must be declared in **config.json** ahead of the alias. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty, indicating that the current ability is not an alias)| -| multiUserShared | Whether the ability supports data sharing among multiple users. This attribute applies only to the ability using the Data template. If this attribute is set to **true**, only one copy of data is stored for multiple users. Note that this attribute will invalidate the **visible** attribute. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**) | -| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**) | -| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean | Yes (initial value: **false**) | -| forms | Details about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | -| srcLanguage | Programming language used to develop the ability. | String | The value can be **js**, or **ets**. | -| srcPath | Path of the JS code and components corresponding to the ability. | String | Yes (initial value: left empty) | +| multiUserShared | Whether the ability supports data sharing among multiple users. This attribute applies only to the ability using the Data template. If this attribute is set to **true**, only one copy of data is stored for multiple users. Note that this attribute will invalidate the **visible** attribute. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | +| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | +| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean| Yes (initial value: **false**) | +| forms | Information about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | +| srcLanguage | Programming language used to develop the ability. The value can be **"js"** or **"ets"**. | String | Yes | +| srcPath | Path of the JS component code corresponding to the ability. | String | Yes (initial value: left empty) | | uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | Yes (initial value: left empty) | -| startWindowBackground | Index to the background color resource file of the ability startup page. Example value: **$color:red**. | String | Yes (initial value: left empty) | +| startWindowIcon | Index to the icon file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$media:icon**.| String | Yes (initial value: left empty)| +| startWindowBackground | Index to the background color resource file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$color:red**.| String | Yes (initial value: left empty)| +| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. This attribute applies only to the ability using the Page template. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| Table 18 Internal structure of the uriPermission attribute @@ -395,8 +402,7 @@ Example of the **abilities** attribute structure: "label": "$media:example", "launchType": "standard", "orientation": "unspecified", - "permissions": [ - ], + "permissions": [], "visible": true, "skills": [ { @@ -416,7 +422,8 @@ Example of the **abilities** attribute structure: ], "type": "page", "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red" + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true }, { "name": ".PlayService", @@ -456,20 +463,20 @@ Table 19 Internal structure of the skills attribute | Attribute| Description | Data Type | Initial Value Allowed | | -------- | ------------------------------------------------------------ | ---------- | -------------------- | | actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)| -| entities | Entities of the **want** that can be accepted by the ability, such as video and Home application.| String array| Yes (initial value: left empty)| +| entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)| | uris | URIs of the **want** that can be accepted by the ability. For details, see Table 20.| Object array | Yes (initial value: left empty)| Table 20 Internal structure of the uris attribute | Attribute | Description | Data Type| Initial Value Allowed | | ------------- | -------------------------- | -------- | -------------------- | -| scheme | Scheme in the URI. | String | No | -| host | Host in the URI. | String | Yes (initial value: left empty)| -| port | Port number in the URI. | String | Yes (initial value: left empty)| -| pathStartWith | **pathStartWith** value in the URI.| String | String | -| path | Path in the URI. | String | Yes (initial value: left empty)| -| pathRegx | **pathRegx** value in the URI. | String | Yes (initial value: left empty)| -| type | Type of the URI. | String | Yes (initial value: left empty)| +| scheme | Scheme of the URI. | String | No | +| host | Host value of the URI. | String | Yes (initial value: left empty)| +| port | Port number of the URI. | String | Yes (initial value: left empty)| +| pathStartWith | **pathStartWith** value of the URI.| String | Yes (initial value: left empty)| +| path | **path** value of the URI. | String | Yes (initial value: left empty)| +| pathRegx | **pathRegx** value of the URI. | String | Yes (initial value: left empty)| +| type | **type** value of the URI. | String | Yes (initial value: left empty)| Example of the **skills** attribute structure: @@ -484,48 +491,49 @@ Example of the **skills** attribute structure: ], "uris": [ { - "scheme": "http", - "host": "www.example.com", - "port": "8080", - "path": "query/student/name", - "type": "text/*" - } - ] + "scheme": "http", + "host": "www.example.com", + "port": "8080", + "path": "query/student/name", + "type": "text/*" + } + ] } ] ``` Table 21 reqPermissions -| Attribute | Description | **Type**| **Value Range** | **Default Value** | **Restrictions** | -| --------- | ------------------------------------------------------------ | -------- | ----------------------------------------------------------- | ---------------------- | ------------------------------------------------------------ | -| name | Permission name, which is mandatory. | String | Custom | None | Parsing will fail if this field is not set. | -| reason | Reason for applying for the permission, which is mandatory only when applying for the **user_grant** permission.| String | The displayed text cannot exceed 256 bytes. | Empty | If the requested permission is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required.| -| usedScene | Application scenario and timing for using the permission, which is mandatory when the requested permission is **user_grant**. This attribute consists of the **ability** and **when** sub-attributes. Multiple abilities can be configured.| Object | **ability**: ability name; **when**: **inuse** or **always**| **ability**: left empty; **when**: **inuse**| If the requested permission is **user_grant**, the **ability** sub-attribute is mandatory and **when** is optional. | +| Attribute | Description | Data Type| Initial Value Allowed | +| ---------- | ------------------------------------------------------------ | -------- | ------------------ | +| name | Name of the permission to request.| String| No| +| reason | Reason for requesting the permission. The value cannot exceed 256 bytes. Multi-language adaptation is required.| String| No if the requested permission is **user_grant** (if it is left empty, application release will be rejected)| +| usedScene | Application scenario and timing for using the permission. This attribute consists of the **ability** and **when** sub-attributes. **ability**: ability name. Multiple ability names can be configured. **when**: time for using the permission. The options are **inuse** and **always**.| Object| **ability**: mandatory for the **user_grant** permission and can be left empty in other cases
**when**: initial value allowed (initial value: **inuse**)| +For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). Table 22 Internal structure of the js attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | ------------------------ | -| name | Name of a JavaScript component. The default value is **default**. | String | No | -| pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | +| name | Name of the JS component. The default value is **default**. | String | No | +| pages | Route information about all pages in the JS component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | | window | Window-related configurations. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 23.| Object | Yes | -| type | Type of the JavaScript component. Available values are as follows:
**normal**: indicates that the JavaScript component is an application instance.
**form**: indicates that the JavaScript component is a widget instance.| String | Yes (initial value: **normal**)| -| mode | Development mode of the JavaScript component. For details, see Table 24. | Object | Yes (initial value: left empty) | +| type | Type of the JS component. Available values are as follows:
**"normal"**: indicates that the JavaScript component is an application instance.
**"form"**: indicates that the JavaScript component is a widget instance. | String | Yes (initial value: **"normal"**) | +| mode | Development mode of the JS component. For details, see Table 24. | Object | Yes (initial value: left empty) | Table 23 Internal structure of the window attribute | Attribute | Description | Data Type| Initial Value Allowed | | --------------- | ------------------------------------------------------------ | -------- | ----------------------- | -| designWidth | Baseline width for page design, in pixels. The size of an element is scaled by the actual device width.| Number | Yes (initial value: 720px) | -| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| +| designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number | Yes (initial value: 720px) | +| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean | Yes (initial value: **false**)| Table 24 Internal structure of the mode attribute | Attribute| Description | Data Type | Initial Value Allowed | | -------- | -------------------- | ----------------------------------- | --------------------------- | -| type | Type of the JavaScript component.| String. The value can be **pageAbility** or **form**.| Yes (initial value: **pageAbility**)| -| syntax | Syntax type of the JavaScript component.| String. The value can be **hml** or **ets**. | Yes (initial value: **hml**) | +| type | Type of the JS component. The value can be **"pageAbility"** or **"form"**. | String | Yes (initial value: **"pageAbility"**) | +| syntax | Syntax type of the JS component. The value can be **"hml"** or **"ets"**. | String | Yes (initial value: **"hml"**) | Example of the **js** attribute structure: @@ -550,8 +558,8 @@ Table 25 Internal structure of the shortcuts attribute | Attribute | Description | Data Type| Initial Value Allowed | | ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| shortcutId | Shortcut ID. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed by the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty)| +| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty)| | icon | Icon of the shortcut. The value is a resource index to the description. | String | Yes (initial value: left empty)| | intents | Intents to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes. For details, see Table 26.| Object array| Yes (initial value: left empty)| @@ -559,7 +567,7 @@ Table 26 Internal structure of the intents attribute | Attribute | Description | Data Type| Initial Value Allowed | | ------------ | --------------------------------------- | -------- | -------------------- | -| targetClass | Class name for the target ability of the shortcut. | String | Yes (initial value: left empty)| +| targetClass | Target class of the shortcut. | String | Yes (initial value: left empty)| | targetBundle | Application bundle name for the target ability of the shortcut.| String | Yes (initial value: left empty)| Example of the **shortcuts** attribute structure: @@ -583,29 +591,29 @@ Table 27 Internal structure of the forms attribute | Attribute | Description | Data Type | Initial Value Allowed | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | +| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | -| type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget.| String | No | +| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | +| type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| -| supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | -| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | -| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | +| supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 1: indicates a grid with two rows and one column.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | +| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String | No | +| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | -| formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | +| formConfigAbility | Name of the facility or activity used to adjust the ability. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | -| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String | No | -| metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute. For details, see Table 13. | Object | Yes (initial value: left empty) | -| customizeData | Custom information about the widget. For details, see Table 28. | Object array | Yes (initial value: left empty) | +| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String | No | +| metaData | Metadata of the widget. The value contains value of the **customizeData** attribute. For details, see Table 13. | Object | Yes (initial value: left empty) | +| customizeData | Custom information of the widget. For details, see Table 28. | Object array | Yes (initial value: left empty) | Table 28 Internal structure of the customizeData attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | --------------------------------------------------- | -------- | -------------------- | -| name | Name in the custom name-value pair. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value in the custom name-value pair. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Format of the current custom data. The value is the resource value of **extra**.| String | Yes (initial value: left empty)| +| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| extra | Current format of the custom data. The value indicates the resource.| String | Yes (initial value: left empty)| Example of the **forms** attribute structure: @@ -629,9 +637,9 @@ Example of the **forms** attribute structure: ] }, { - "name": "Form_JS", + "name": "Form_Js", "description": "It's JS Form", - "type": "JS", + "type": "Js", "colorMode": "auto", "isDefault": false, "updateEnabled": true, @@ -662,13 +670,13 @@ Example of the **forms** attribute structure: Table 29 Internal structure of the distroFilter attribute -| Attribute | Description | Data Type| Initial Value Allowed| -| ------------- | ------------------------------------------------------------ | -------- | ---------- | -| apiVersion | Supported API versions. For details, see Table 30. | Object | No | -| screenShape | Supported screen shapes. For details, see Table 31. | Object array| No | -| screenWindow | Supported window resolutions when the application is running. This attribute applies only to the lite wearables. For details, see Table 32.| Object array| No | -| screenDensity | Pixel density of the screen, in dots per inch (DPI). For details, see Table 33. | Object array| No | -| countryCode | Country code used during application distribution. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported. For details, see Table 34.| Object array| No | +| Attribute | Description | Data Type| Initial Value Allowed | +| ------------- | ------------------------------------------------------------ | -------- | -------------------- | +| apiVersion | Supported API versions. For details, see Table 30. | Object | Yes (initial value: left empty)| +| screenShape | Supported screen shapes. For details, see Table 31. | Object array| Yes (initial value: left empty)| +| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables. For details, see Table 32.| Object array| Yes (initial value: left empty)| +| screenDensity | Pixel density of the screen, in dots per inch (dpi). For details, see Table 33. | Object array| Yes (initial value: left empty)| +| countryCode | Country code used for distributing the application. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported. For details, see Table 34.| Object array| Yes (initial value: left empty)| Table 30 Internal structure of the apiVersion attribute @@ -727,7 +735,7 @@ Example of the **distroFilter** attribute structure: }, "countryCode": { "policy":"include", - "value":["CN", "HK"] + "value":["CN","HK"] } } ``` @@ -738,7 +746,7 @@ Table 35 Internal structure of the commonEvents attribute | ---------- | ------------------------------------------------------------ | ---------- | ------------------ | | name | Name of a static broadcast. | String | No | | permission | Permission needed to implement the static common event. | String array| Yes (initial value: left empty)| -| data | Additional data array to be carried by the current static common event. | String array| Yes (initial value: left empty)| +| data | Additional data array to be carried by the current static common event. | String array| Yes (initial value: left empty)| | type | Type array of the current static common event. | String array| Yes (initial value: left empty)| | events | A set of events for the wants that can be received. The value can be system predefined or custom.| String array| No | @@ -746,17 +754,44 @@ Example of the **commonEvents** attribute structure: ```json "commonEvents": [ - { - "name":"MainAbility", - "permission": "string", - "data":[ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - } + { + "name":"MainAbility", + "permission": "string", + "data":[ + "string", + "string" + ], + "events": [ + "string", + "string" + ] + } ] ``` + +Table 36 Internal structure of the testRunner attribute + +| Attribute| Description | Data Type| Initial Value Allowed| +| -------- | -------------------- | -------- | ---------- | +| name | Name of the test runner object.| String | No | +| srcPath | Path of the test runner code.| String | No | + +```json +"testRunner": { + "name": "myTestRUnnerName", + "srcPath": "etc/test/TestRunner.ts" +} +``` + +Table 37 Internal structure of the definePermissions attribute +**definePermission** applies only to system applications and does not take effect for third-party applications. + +| Attribute | Description | Data Type| Initial Value Allowed| +| ----------------------- | ------------------------------------------------------------ | -------- | ---------- | +| name | Permission name. | String | No | +| grantMode | Permission grant mode.
Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user. | String | Yes (initial value: **"system_grant"**) | +| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | +| provisionEnable | Whether the permission can be requested in provision mode. | Boolean | Yes (initial value: **true**) | +| distributedSceneEnabled | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | +| label | Brief description of the permission. The value is a resource index. | String | Yes | +| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes | diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index bd1eb5a1a3f52c392a645b8958e02e2f59e39e29..03845296847a43338cca31673b76e46b8c496bbf 100644 --- a/en/application-dev/quick-start/stage-structure.md +++ b/en/application-dev/quick-start/stage-structure.md @@ -2,20 +2,22 @@ # Application Package Structure Configuration File -When developing an application in the FA model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json** file. +When developing an application in the Feature Ability (FA) model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json5** and **app.json** files. -## Internal Structure of the module.json File +## Configuration File Internal Structure -The **module.json** file consists of two tags: **app** and **module**. See Table 1 for details. +The configuration files each consist of two mandatory tags, namely, **app** and **module**. For details, see Table 1. -Table 1 Internal structure of the module.json file +Table 1 Configuration file internal structure | Tag| Description | Data Type| Initial Value Allowed| | -------- | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of an application. Different HAP files of an application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| module | Configuration of a HAP file. The **module** configuration is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | +| app | Global configuration of the application. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | +| module | Configuration of the HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | -Example of the **module.json** file: +### Internal Structure of the app Tag + +Code snippet in the **app.json** file: ```json { @@ -25,8 +27,8 @@ Example of the **module.json** file: "versionCode": 1, "versionName": "1.0", "minCompatibleVersionCode": 1, - "apiCompatibleVersion": 7, - "apiTargetVersion": 8, + "minAPIVersion": 7, + "targetAPIVersion": 8, "apiReleaseType": "Release", "debug": false, "icon": "$media:app_icon", @@ -37,20 +39,56 @@ Example of the **module.json** file: "car": { "apiCompatibleVersion": 8 } - }, + } +} +``` + +This tag is an application-level attribute that applies to all the HAP files and components in the application. For the internal structure of the tag, see Table 2. + +Table 2 Internal structure of the app tag + +| Attribute | Description | Data Type| Initial Value Allowed | +| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | +| bundleName | Bundle name that uniquely identifies the application. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
For an application compiled with the system source code, its bundle name must be in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony. | String | No | +| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | +| icon | Icon of the application. The value is the index to the resource file. | String | No | +| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | +| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | +| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | +| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | +| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | +| minCompatibleVersionCode | Earliest version that the application is compatible with. It is used to determine cross-device compatibility. | Number | Yes (initial value: value of **versionCode**)| +| minAPIVersion | Minimum API version required for running the application. | Integer | Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| +| targetAPIVersion | Target API version required for running the application. | Integer | Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| +| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | +| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | +| entityType | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: **"unspecified"**) | +| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8. | Boolean | Yes (initial value: **false**) | +| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | +| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | +| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | +| accessible | Whether the installation directory of the application is accessible. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the installation directory can be accessed by third-party applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | +| multiProjects | Whether multiple projects are supported.| Boolean| Yes (initial value: **false**)| +| deviceType | Supported device types, such as **tablet**, **tv**, **wearable**, and **car**. The following attributes may be included: **minAPIVersion**, **distributedNotificationEnabled**, **keepAlive**, and **removable**.| Object | Yes (initial value: settings under **"app"**)| + +### Internal Structure of the module Tag + +Code snippet in the **module.json5** file: + +```json +{ "module": { "name": "myHapName", "type": "entry|feature|har", "srcEntrance" : "./MyAbilityStage.js", "description" : "$string:description_application", - "process": "string", "mainElement": "MainAbility", "deviceTypes": [ "tablet", "tv", "wearable", "car", - "router", + "router" ], "deliveryWithInstall": true, "installationFree": false, @@ -67,18 +105,6 @@ Example of the **module.json** file: "resource": "$profile:config_file2" } ], - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file1" - }, - { - "name": "string", - "value": "string", - "resource": "$profile:config_file2" - } - ], "abilities": [ { "name": "MainAbility", @@ -109,38 +135,18 @@ Example of the **module.json** file: "voip", "taskKeeping" ], - } - ], - "abilities": [ + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red" + }, { - "name": "MainAbility", - "srcEntrance" : "./login/MyMainAbility.ts", - "description": "$string:description_main_ability", + "name": "sampleAbility", + "srcEntrance" : "./login/sampleAbility.ts", + "description": "$string:description_sample_ability", "icon": "$media:icon", "label": "HiMusic", "visible": true, - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ ] - } - ], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" - ], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red" } ], "requestPermissions": [ @@ -159,79 +165,56 @@ Example of the **module.json** file: } ``` -### Internal Structure of the app Tag - -This tag is an application-level attribute that affects all the HAP files and components in the application. For the internal structure of the tag, see Table 2. - -Table 2 Internal structure of the app tag - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | -| bundleName | Bundle name that uniquely identifies the application. This attribute cannot be left empty. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*. The first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
The application compiled with the system source code must be named in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony.| String | No | -| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | -| icon | Icon of the application. The value is the index to the resource file. | String | No | -| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | -| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | -| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | -| minCompatibleVersionCode | Minimum API version compatible with the application. | Number | Yes (initial value: value of **versionCode**)| -| minAPIVersion | Minimum API version required for running the application. | Number | No | -| targetAPIVersion | Target API version required for running the application. | Integer | No | -| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | -| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | -| entityType | Type of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: unspecified) | - -### Internal Structure of the module Tag - This tag stores the HAP configuration, which only applies to the current HAP file. Table 3 Internal structure of the module tag -| Attribute | Description | Data Type | Initial Value Allowed | -| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------- | -| name | Name of the current module. After the module is packed into a HAP file, this attribute indicates the name of the HAP file. The value is a string with a maximum of 31 bytes and must be unique in the entire application.| String | No | -| type | Type of the current HAP file. There are three types: **entry**, **feature**, and **har**.| String | No | -| srcEntrance | Path of the entry JS code corresponding to the HAP file. The value is a string with a maximum of 127 bytes.| String | Yes | -| description | Description of the HAP file. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| process | Process of the HAP file. The value is a string with a maximum of 31 bytes. If a process is configured under **hap**, all abilities of the application run in this process.| String | Yes (initial value: name of the HAP file) | -| mainElement | Entrance ability name or extension name of the HAP file. Only the ability or extension whose value is **mainElement** can be displayed in the Service Center. This attribute cannot be left at the initial value for an OpenHarmony atomic service.| String | Yes for an OpenHarmony application | -| deviceTypes | Types of the devices on which the HAP file can run. Table 4 lists the device types predefined by the system.
Different from **syscap**, which is based on the device capability (such as Bluetooth and Wi-Fi), **deviceTypes** is based on the device type.| String array| No (can be left empty) | -| deliveryWithInstall | Whether the current HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| Boolean | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.

When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap** must be **true**.
When **entry.hap** is set to **false**, **feature.hap** fields related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| virtualMachine | Type of the target virtual machine (VM) where the current HAP file is running. It is used for cloud distribution, such as the application market and distribution center.
If the target VM type is Ark, the value is **ark**. Otherwise, the value is **default**. This attribute is automatically inserted when the IDE builds the HAP file. When the decompression tool parses the HAP file, if the HAP file does not contain this attribute, the value is set to **default**. | String | Yes (initial value: **default**) | -| uiSyntax | Syntax type of the JS component.
**hml**: indicates that the JS component is developed using HML, CSS, or JS.
**ets**: indicates that the JS component is developed using the eTS declarative syntax.| String | Yes (initial value: **hml**) | -| pages | Profile resource used to list information about each page in the JS component. For details about how to use **pages**, see the **pages** example.| Object | No in the ability scenario| -| metadata | Custom metadata of the HAP file. The configuration is valid only for the current module, ability, or extensionAbility. For details about **metadata**, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | -| abilities | Metadata capability configuration, which is valid only for the current ability. For details about **abilities**, see [Internal Structure of the abilities Attribute](#internal-structure-of-the-abilities-attribute).| Object | Yes (initial value: left empty) | -| extensionAbilities | Configuration of extensionAbilities, which is valid only for the current extensionAbility. For details about **extensionAbilities**, see [Internal structure of the extensionAbility attribute](#internal-structure-of-the-extensionability-attribute).| Object | Yes (initial value: left empty) | -| requestPermissions | A set of permissions that the application needs to apply for from the system when the application is running. For details about **requestPermissions**, see [Internal structure of the requestPermissions attribute](#internal-structure-of-the-requestpermissions-attribute).| Object | Yes (initial value: left empty) | +| Attribute | Description | Data Type | Initial Value Allowed | +| -------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| name | Name of the current module. After the module is packed into a HAP file, this attribute indicates the name of the HAP file. The value is a string with a maximum of 31 bytes and must be unique in the entire application.| String | No | +| type | Type of the HAP file. There are three types: **entry**, **feature**, and **har**.| String | No | +| srcEntrance | Path of the entry JS code corresponding to the HAP file. The value is a string with a maximum of 127 bytes.| String | Yes | +| description | Description of the HAP file. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | +| process | Process of the HAP file. The value is a string with a maximum of 31 bytes. If a process is configured under **hap**, all abilities of the application run in this process. This attribute applies only to system applications.| String | Yes (initial value: value of **bundleName** under the **app** tag) | +| mainElement | Entrance ability name or extension name of the HAP file. Only the ability or extension whose value is **mainElement** can be displayed in the Service Center. This attribute cannot be left at the initial value for an OpenHarmony atomic service.| String | Yes for an OpenHarmony application | +| deviceTypes | Types of the devices on which the HAP file can run. Table 4 lists the device types predefined by the system.
Unlike **syscap**, which is based on the device capability (such as Bluetooth and Wi-Fi), **deviceTypes** is based on the device type.| String array| No (can be left empty) | +| deliveryWithInstall | Whether the current HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| Boolean | No | +| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.

When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap** must be **true**.
When **entry.hap** is set to **false**, **feature.hap** fields related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | +| virtualMachine | Type of the target virtual machine (VM) where the current HAP file is running. It is used for cloud distribution, such as the application market and distribution center.
If the target VM type is Ark, the value is **ark**. Otherwise, the value is **default**. This attribute is automatically inserted when the IDE builds the HAP file. When the decompression tool parses the HAP file, if the HAP file does not contain this attribute, the value is set to **default**. | String | Yes (initial value: **default**) | +| uiSyntax(deprecated) | Syntax type of the JS component. This attribute is deprecated since API version 9.
**"hml"**: indicates that the JS component is developed using HML, CSS, or JS.
**"ets"**: indicates that the JS component is developed using the eTS declarative syntax.| String | Yes (initial value: **"hml"**) | +| pages | Profile resource used to list information about each page in the JS component. For details about how to use **pages**, see the **pages** example.| Object | No in the ability scenario | +| metadata | Custom metadata of the HAP file. The configuration is valid only for the current module, ability, or extensionAbility. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | +| abilities | Ability configuration, which is valid only for the current ability. For details, see [Internal Structure of the abilities Attribute](#internal-structure-of-the-abilities-attribute).| Object | Yes (initial value: left empty) | +| extensionAbilities | Extension ability configuration, which is valid only for the current Extension ability. For details, see [Internal structure of the extensionAbility attribute](#internal-structure-of-the-extensionability-attribute).| Object | Yes (initial value: left empty) | +| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The callers must acquire these permissions before calling the application. For details, see [Internal structure of the definePermissions attribute](#internal-structure-of-the-definepermissions-attribute).| Object | Yes (initial value: left empty)| +| requestPermissions | A set of permissions that the application needs to request from the system when the application is running. For details, see [Internal structure of the requestPermissions attribute](#internal-structure-of-the-requestpermissions-attribute). | Object | Yes (initial value: left empty) | +| testRunner | Test runner configuration. For details, see [Internal structure of the testRunner attribute](#internal-structure-of-the-testrunner-attribute).| Object | Yes (initial value: left empty) | Table 4 System-defined deviceTypes values -| Device Type | Value | Description | -| ------------ | ------------ | -------------------------------------------------------- | -| tablet | tablet | Tablet, speaker with a screen | -| smart TV | tv | N/A | -| smart watch | wearable | Smart watch, kids' watch, especially a watch that provides call features| -| head unit | car | N/A | -| router | router | Router | +| Value | Device Type | +| -------- | -------------------------------------------------------- | +| tablet | Tablet, speaker with a screen | +| tv | Smart TV | +| wearable | Smart watch, kids' watch, especially a watch that provides call features| +| car | Head unit | +| router | Router | Example of the **deviceTypes** attribute structure: ```json { - "module": { - "name": "myHapName", + "module": { + "name": "myHapName", "type": "har", "deviceTypes" : [ "wearable" ] - } + } } ``` -Example of the **pages** attribute structure:: +Example of the **pages** attribute structure: ```json { @@ -269,8 +252,8 @@ Table 5 Internal structure of the metadata attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------------- | -| name | Name of a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | +| name | Name of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | | resource | Custom data format. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty) | Example of the **metadata** attribute structure: @@ -304,17 +287,28 @@ Table 6 Internal structure of the abilities attribute | --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | | name | Logical name of the ability, which must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String | No | | srcEntrance | JS code path corresponding to the ability. The value is a string with a maximum of 127 bytes.| String | No | -| launchType | Ability startup mode. The value can be **standard**, **singleton**, or **specified**. The default value is **singleton**. The value **standard** indicates common multi-instance, the value **singleton** indicates a singleton, and the value **specified** indicates one or more specified instances, depending on the internal service of the ability.| String | Yes (initial value: **singleton**) | +| launchType | Ability startup mode. Available values are as follows:
**"standard"**: indicates common multi-instance.
**"singleton"**: indicates a singleton.
**"specified"**: indicates one or more specified instances, depending on the internal service of the ability. | String | Yes (initial value: **singleton**) | | description | Ability description. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the ability. The value is the index to the resource file. This attribute can be left empty, and the default value is an empty array.
If **ability** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| -| permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value must be the same as the **name** value of a permission defined in the **defPermissions** attribute. | String array| Yes (initial value: left empty) | -| metadata | Metadata about the ability. For details about metadata, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | +| icon | Icon of the ability. The value is the index to the resource file. | String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| +| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | +| metadata | Metadata of the ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | | visible | Whether the ability can be invoked by other applications. The value **true** means that the ability can be invoked by other applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | | continuable | Whether the ability can be migrated. The value **true** means that the ability can be migrated, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.
For details about the internal structure of **skills**, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute).| Array | Yes (initial value: left empty) | +| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | | backgroundModes | Continuous task modes of the ability.
Continuous tasks are classified into the following types:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables)
**multiDeviceConnection**: multi-device interconnection service
**wifiInteraction**: Wi-Fi scanning, connection, and transmission services (multi-screen cloning)
**voip**: voice/video call and VoIP services
**taskKeeping**: computing service
| String | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | No | -| startWindowBackground | Index to the background color resource file of the ability startup page. Example value: **$color:red**. | String | No | +| startWindowIcon | Index to the icon file of the ability startup page. Example: **$media:icon**.| String | No| +| startWindowBackground | Index to the background color resource file of the ability startup page. Example: **$color:red**.| String | No| +| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| +| orientation | Display orientation of the ability when it is started. Available values are as follows:
**"unspecified"**: The device orientation is auto-set by the system.
**"landscape"**: The device is in landscape orientation.
**"portrait"**: The device is in portrait orientation.
**"landscape_inverted"**: The device is in inverted landscape orientation.
**"portrait_inverted"**: The device is in inverted portrait orientation.
**"auto_rotation"**: The device orientation is determined by the sensor.
**auto_rotation_landscape**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape.
**auto_rotation_portrait**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait.
**auto_rotation_restricted**: The device orientation is determined by the sensor when the sensor switch is enabled.
**auto_rotation_landscape_restricted**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape, when the sensor switch is enabled.
**auto_rotation_portrait_restricted**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait, when the sensor switch is enabled.
**locked**: Auto rotate is disabled.| String | Yes (initial value: **"unspecified"**)| +|supportWindowMode|Window display mode of the ability. Available values are as follows:
**fullscreen**: full-screen mode.
**split**: split-screen mode.
**floating**: floating window mode.|Array | Yes (initial value:
["fullscreen", "split", "floating"])| +|priority|Priority of the ability. This attribute applies only to system applications and does not take effect for third-party applications. During implicit query, an ability with a higher the priority is closer to the top of the returned list. The value is an integer ranging from 0 to 10. A larger value indicates a higher priority.|Number| Yes (initial value: **0**)| +|maxWindowRatio|Maximum aspect ratio of the ability.| Number |Yes (initial value: maximum aspect ratio of the platform)| +|minWindowRatio|Minimum aspect ratio of the ability.| Number |Yes (initial value: minimum aspect ratio supported by the platform)| +|maxWindowWidth|Maximum window width of the ability, in vp.| Number |Yes (initial value: maximum window width supported by the platform)| +|minWindowWidth|Minimum window width of the ability, in vp.| Number |Yes (initial value: minimum window width supported by the platform)| +|maxWindowHeight|Maximum window height of the ability, in vp.| Number |Yes (initial value: maximum window height supported by the platform)| +|minWindowHeight|Minimum window height of the ability, in vp.| Number |Yes (initial value: minimum window height supported by the platform)| +| excludeFromMissions | Whether the ability is excluded from the recent tasks list. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** indicates that the task is excluded from the recent tasks list, and **false** indicates that the task is displayed in the recent tasks list.| Boolean | Yes (initial value: **false**)| Example of the **abilities** attribute structure: @@ -323,7 +317,7 @@ Example of the **abilities** attribute structure: "abilities": [{ "name": "MainAbility", "srcEntrance": "./ets/login/MyLoginAbility.ts", - "launchType":"standard" + "launchType":"standard", "description": "$string:description_main_ability", "icon": "$media:icon", "label": "Login", @@ -347,7 +341,19 @@ Example of the **abilities** attribute structure: "voip", "taskKeeping" ], - }], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true, + "orientation": " ", + "supportWindowMode": ["fullscreen", "split", "floating"], + "maxWindowRatio": 3.5, + "minWindowRatio": 0.5, + "maxWindowWidth": 2560, + "minWindowWidth": 1400, + "maxWindowHeight": 300, + "minWindowHeight": 200, + "excludeFromMissions": false + }] } ``` @@ -361,17 +367,17 @@ Table 7 Internal structure of the skills attribute | -------- | ------------------------------------------------------------ | ---------- | -------------------- | | actions | A set of want action values that can be received. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| | entities | Categories of abilities that can receive the want. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| -| uris | Data specification to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details about the internal structure of **uris**, see Table 8.| Object array | Yes (initial value: left empty)| +| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details, see Table 8.| Object array | Yes (initial value: left empty)| Table 8 Internal structure of the uris attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------- | -------- | -------------------- | -| scheme | Scheme in the URI.| String | No | -| host | Host in the URI. | String | Yes (initial value: left empty)| -| port | Port number in the URI. | String | Yes (initial value: left empty)| -| path | Path in the URI. | String | Yes (initial value: left empty)| -| type | Type of the URI. | String | Yes (initial value: left empty)| +| scheme | Scheme of the URI.| String | No | +| host | Host value of the URI. | String | Yes (initial value: left empty)| +| port | Port number of the URI. | String | Yes (initial value: left empty)| +| path | **path** value of the URI. | String | Yes (initial value: left empty)| +| type | **type** value of the URI. | String | Yes (initial value: left empty)| Example of the **skills** attribute structure: @@ -396,10 +402,10 @@ Example of the **skills** attribute structure: "pathRegex":"/query/.*", "path":"path", "type": "text/*" - }, + } ] } - ], + ] } ], "extensionAbilities": [ @@ -419,34 +425,34 @@ Example of the **skills** attribute structure: "pathRegex":"/query/.*", "path":"path", "type": "text/*" - }, + } ] } - ], + ] } - ], + ] } ``` #### Internal Structure of the extensionAbility Attribute -The **extensionAbility** attribute describes the configuration information of **extensionAbility**. The configuration is valid only for the current extensionAbility. +The **extensionAbility** attribute describes the configuration information of the current Extension ability. Table 9 Internal structure of the extensionAbility attribute | Attribute | Description | Data Type | Initial Value Allowed | | ----------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Logical name of the current extensionAbility. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String | No | -| srcEntrance | JS code path corresponding to extensionAbility. The value is a string with a maximum of 127 bytes.| String | No | -| description | Description of the extensionAbility. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the extensionAbility. The value is the index to the resource file. If **extensionAbility** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty) | -| label | Name of the extensionAbility displayed to users. The value is a resource index to names in multiple languages.
If **extensionAbility** is set to **MainElement**, this attribute is mandatory and the value must be unique in the application.| String | No | -| type | Type of the extension capability. The value can be form, workScheduler, inputMethod, service, accessibility, dataShare, fileShare, staticSubscriber, wallpaper, or backup. | String | No | +| name | Logical name of the current Extension ability. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String | No | +| srcEntrance | JS code path corresponding to the Extension ability. The value is a string with a maximum of 127 bytes.| String | No | +| description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | +| icon | Icon of the Extension ability. The value is the index to the resource file. If **extensionAbility** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty) | +| label | Name of the Extension ability displayed to users. The value is a resource index to names in multiple languages.
If **extensionAbility** is set to **MainElement**, this attribute is mandatory and the value must be unique in the application.| String | No | +| type | Type of the Extension ability. The value can be **"form"**, **"workScheduler"**, **"inputMethod"**, **"service"**, **"accessibility"**, **"dataShare"**, **"fileShare"**, **"staticSubscriber"**, **"wallpaper"**, **"backup"**, **"window"**, **"enterpriseAdmin"**, **"thumbnail"**, or **"preview"**.| String | No | | permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty) | | uri | Data URI provided by the ability. The value is an array containing a maximum of 255 characters and is in the format of a reverse domain name. This attribute is mandatory when **type** is set to **extensionAbility** of the dataShare type.| String | Yes (initial value: left empty) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.
For details about the internal structure of **skills**, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute).| Array | Yes (initial value: left empty) | -| metadata | Metadata of extensionAbility. For details about metadata, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Object | Yes (initial value: left empty) | -| visible | Whether extensionAbility can be invoked by other applications. The value is of the Boolean type. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| | Yes (initial value: **false**)| +| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | +| metadata | Metadata of the Extension ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Object | Yes (initial value: left empty) | +| visible | Whether extensionAbility can be invoked by other applications. The value is of the Boolean type. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| Boolean | Yes (initial value: **false**)| Example of the **extensionAbility** attribute structure: @@ -475,29 +481,47 @@ Example of the **extensionAbility** attribute structure: "name": "ohos.extability.form", "resource": "$profile:form_config", } - ], + ] } ] } ``` +#### Internal Structure of the definePermissions Attribute + +The **definePermissions** attribute indicates the permissions defined for the HAP file. + +Table 10 Internal structure of the definePermissions attribute + +| Attribute | Description | Data Type| Initial Value Allowed | +| ---------------------- | ------------------------------------------------------------ | -------- | ------------------------------ | +| name | Permission name. | String | No | +| grantMode | Permission grant mode. Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user.| String | Yes (initial value: **"system_grant"**)| +| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | +| provisionEnable | Whether to enable provision mode for requesting permissions, including higher-level permissions. The value **true** indicates that provision mode is enabled.| Boolean | Yes (initial value: **true**) | +| distributedSceneEnable | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | +| label | Brief description of the permission. The value is a resource index. | String | Yes (initial value: left empty) | +| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes (initial value: left empty) | + #### Internal Structure of the requestPermissions Attribute -This attribute identifies a set of permissions that the application needs to apply for from the system when the application is running. +This attribute identifies a set of permissions that the application needs to request from the system when the application is running. -Table 10 requestPermissions attributes +Table 11 Internal structure of the requestPermissions attribute -| Attribute | Description | **Type** | **Value Range** | **Default Value** | **Restrictions** | -| --------- | ------------------------------------------------------------ | ------------------------------- | ----------------------------------------------------------- | ---------------------- | ------------------------------------------------------------ | -| name | Permission name. This attribute is mandatory. | String | Custom | None | Parsing will fail if this field is not set. | -| reason | Reason for requesting the permission. This attribute is mandatory when the requested permission is **user_grant**. | String | The maximum length is 256 bytes. | Empty | If the requested permission is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required. | -| usedScene | Application scenario and timing for using the permission, which is mandatory when the requested permission is **user_grant**. This attribute consists of the **ability** and **when** sub-attributes. Multiple abilities can be configured. | **ability**: string array; **when**: string | **ability**: ability name; **when**: **inuse** or **always** | **ability**: left empty; **when**: **inuse** | If the requested permission is **user_grant**, the **ability** sub-attribute is mandatory and **when** is optional. | +| Attribute | Description | Type | Value Range | Default Value | Restrictions | +| --------- | ------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ | +| name | Permission name. This attribute is mandatory. | String | Custom | N/A | Parsing will fail if this attribute is not set. | +| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**. | String | Resource reference of the string type in `$string: ***` format | Empty | If the permission to request is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required.| +| usedScene | Application scenario and timing for using the permission. This attribute is mandatory when the permission to request is **user_grant**. It consists of the **abilities** and **when** sub-attributes. Multiple abilities can be configured.| **abilities**: string array; **when**: string| **abilities**: array of ability names; **when**: **inuse** and **always**| **abilities**: left empty; **when**: left empty| If the permission to request is **user_grant**, the **abilities** sub-attribute is mandatory and **when** is optional. | Example of the **requestPermissions** attribute structure: ```json { + "name": "ohos.abilitydemo.permission.PROVIDER", + "reason": "$string:reason", "usedScene": { "abilities": [ "AudioAbility", @@ -507,34 +531,38 @@ Example of the **requestPermissions** attribute structure: } } ``` +For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). #### Internal Structure of the form Attribute The **forms** attribute indicates the service widget configuration. The service widget is an application brief view that can be displayed on the home screen and periodically updated. You can include the **forms** attribute in any of the following modes: 1. Set **type** to **form** in **extensions**. -2. Specify the **form** information in **metadata**, where: - - **name** indicates the name of the service widget, for example, **ohos.extability.form**. - - **resource** indicates where the resources of the service widget are stored. - -Table 11 Internal structure of the forms attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ----------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | -| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| src | UI code of a JS service widget. It is recommended that you use the adaptive layout to display a service widget of different specifications. If the layout of a service widget of different specifications differs greatly, you are advised to use different service widgets.| String | Yes (initial value: left empty) | -| window | Adaptive capability of a JS service widget. For details about the window structure, see Table 12. | Object | Yes (initial value: left empty) | -| isDefault | Whether the service widget is the default one. Each ability has only one default service widget. **true**: The service widget is the default one. **false**: The service widget is not the default one.| Boolean | No | -| colorMode | Theme style of the service widget. The value can be **auto**, **dark**, or **light**.| String | Yes (initial value: **auto**) | -| supportDimensions | Dimensions supported by the service widget. The value can be **1 * 2**, **2 * 2**, **2 * 4**, or **4 * 4**, where the number before the asterisk (*) indicates the number of rows, and the number after the asterisk (*) indicates the number of columns.| String array| No | -| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | -| updateDuration | Update frequency of a widget. The unit is 30 minutes. The value is a multiple of 30. The highest frequency of refreshing a widget is once every 30 minutes. You can also use scheduled refresh to refresh a widget at a fixed time or once every 30 minutes. If both of them are configured, the scheduled refresh takes precedence.| Number | Yes (initial value: left empty) | -| metadata | Custom information about a widget. For details about the internal structure of metadata, see Table 5. | Object | Yes (initial value: left empty) | -| formConfigAbility | Ability name for widget adjustment. The value is a string of up to 127 characters. The value must be in the following format:
ability:// Name of an ability.
The name must be the same as that of the current application.| String | Yes (initial value: left empty) | -| formVisibleNotify | Whether the widget is allowed to use the visibility notification. The value is **true** or **false**.| Boolean | Yes (initial value: **false**)| - -Table 12 Internal structure of window + +2. Specify the **form** information in **metadata**, where: + - **name** indicates the name of the service widget, for example, **ohos.extability.form**. + - **resource** indicates where the resources of the service widget are stored. + +Table 12 Internal structure of the forms attribute + +| Attribute | Description | Data Type | Initial Value Allowed | +| ------------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | +| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | +| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | +| src | UI code of a JS service widget. It is recommended that you use the adaptive layout to display a service widget of different specifications. If the layout of a service widget of different specifications differs greatly, you are advised to use different service widgets.| String | Yes (initial value: left empty) | +| window | Adaptive capability of a JS service widget. For details, see Table 12. | Object | Yes (initial value: left empty) | +| isDefault | Whether the widget is a default one. Each ability has only one default widget. **true**: The service widget is the default one. **false**: The service widget is not the default one.| Boolean | No | +| colorMode | Color mode of the widget. The value can be **auto**, **dark**, or **light**.| String | Yes (initial value: **auto**) | +| supportDimensions | Dimensions supported by the service widget. The value can be **1 * 2**, **2 * 1**, **2 * 2**, **2 * 4**, or **4 * 4**, where the number before the asterisk (*) indicates the number of rows, and the number after the asterisk (*) indicates the number of columns.| String array| No | +| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String | No | +| updateEnabled | Whether the widget can be updated periodically. The value **true** indicates that the widget can be updated periodically, and **false** indicates that the widget cannot be updated periodically.| Boolean | No | +| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes | +| updateDuration | Update frequency of a widget. The unit is 30 minutes. The value is a multiple of 30. The highest frequency of refreshing a widget is once every 30 minutes. You can also use scheduled refresh to refresh a widget at a fixed time or once every 30 minutes. If both of them are configured, the scheduled refresh takes precedence.| Number | Yes (initial value: left empty) | +| metadata | Metadata of the widget. For details, see Table 5. | Object | Yes (initial value: left empty) | +| formConfigAbility | Ability name for widget adjustment. The value is a string of up to 127 characters. The value must be in the following format:
ability:// Name of an ability.
The name must be the same as that of the current application.| String | Yes (initial value: left empty) | +| formVisibleNotify | Whether the widget is allowed to use the visibility notification. The value is **true** or **false**.| Boolean | Yes (initial value: **false**)| + +Table 13 Internal structure of the window attribute | Attribute | Description | Data Type| Initial Value Allowed | | --------------- | ------------------------------------------------------------ | -------- | -------------------- | @@ -564,10 +592,12 @@ Define the **form_config.json** file (this file name is customizable) in **resou "scheduledUpdateTime": "10:30", "updateDuration": 1, "defaultDimension": "2*2", + "updateEnabled": true, + "scheduledUpdateTime": "21:33", "supportDimensions": [ "2*2" ], - "metadata": [ + "metadata": [ { "name": "string", "value": "string", @@ -579,22 +609,18 @@ Define the **form_config.json** file (this file name is customizable) in **resou } ``` -Define metadata information in the **extension** component of the **module.json** file. +Define metadata information in the **extension** component of the **module.json5** file. ```json { - "extensionAbilities": [ - { - "name": "MyForm", - "type": "form", - "metadata": [ - { - "name": "ohos.extability.form", - "resource": "$profile:form_config", - } - ], - } - ] + "extensionAbilities": [{ + "name": "MyForm", + "type": "form", + "metadata": [{ + "name": "ohos.extability.form", + "resource": "$profile:form_config" + }] + }] } ``` @@ -604,16 +630,16 @@ This attribute identifies the shortcut information of an application. The value Specify the **shortcut** information in **metadata**, where: -- **name** indicates the name of the shortcut, for example, **ohos.ability.shortcut**. +- **name** indicates the name of the shortcut, for example, **ohos.ability.shortcuts**. - **resource** indicates where the resources of the shortcut are stored. -Table 13 Internal structure of the shortcuts attribute +Table 14 Internal structure of the shortcuts attribute | Attribute | Description | Data Type| Initial Value Allowed | | ---------- | ------------------------------------------------------------ | -------- | -------------------------- | | shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed by the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty) | +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty) | | icon | Icon of the shortcut. The value is the index to the resource file. | String | Yes (initial value: left empty)| | wants | Wants to which the shortcut points. The attribute consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut; string type.
**abilityName**: target component name of the shortcut; string type.| Object | Yes (initial value: left empty) | @@ -621,45 +647,37 @@ Define the **shortcut_config.json** file (this file name is customizable) in **r ```json { - "shortcuts": [ - { - "shortcutId": "id_test1", - "label": "$string:shortcut", - "icon": "$media:aa_icon", - "wants": [ - { - "bundleName": "com.ohos.hello" - "abilityName": "MainAbility" - } - ] - } - ] + "shortcuts": [{ + "shortcutId": "id_test1", + "label": "$string:shortcut", + "icon": "$media:aa_icon", + "wants": [{ + "bundleName": "com.ohos.hello", + "abilityName": "MainAbility" + }] + }] } ``` -Define the **metadata** information under **module** in the **config.json** file as follows: +Define the **metadata** information under **module** in the **module.json5** file as follows: ```json { "module": { "name": "MyAbilityStage", - "abilities" : [ - { - "name" : "MyAbility", - "srcEntrance": "./abilities/MyAbility.ts", - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "metadata": [ - { - "name": "ohos.ability.shortcut", - "resource": "$profile:shortcuts_config", - } - ], - } - ] + "abilities": [{ + "name": "MyAbility", + "srcEntrance": "./abilities/MyAbility.ts", + "skills": [{ + "actions": ["action.system.home"], + "entities": ["entity.system.home"], + "uris": [] + }], + "metadata": [{ + "name": "ohos.ability.shortcuts", + "resource": "$profile:shortcuts_config" + }] + }] } } ``` @@ -674,7 +692,7 @@ Specify the **commonEvent** information in the **metadata**, where: - **resource** indicates where the resources of the common event are stored. -Table 14 Internal structure of the commonEvents attribute +Table 15 Internal structure of the commonEvents attribute | Attribute | Description | Data Type | Initial Value Allowed | | ---------- | ------------------------------------------------------------ | ---------- | -------------------------- | @@ -687,24 +705,22 @@ Define the **common_event_config.json** file in **resources/base/profile** in th ```json { - "commonEvents": [ - { - "name": "abilityName", - "permission": "string", - "types": [ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - } - ] + "commonEvents": [{ + "name": "abilityName", + "permission": "string", + "types": [ + "string", + "string" + ], + "events": [ + "string", + "string" + ] + }] } ``` -Define the **metadata** information under **extension** in the **module.json** file as follows: +Define the **metadata** information under **extension** in the **module.json5** file as follows: ```json "extensionAbilities": [ @@ -712,66 +728,64 @@ Define the **metadata** information under **extension** in the **module.json** f "name": "mySubscriber", "srcEntrance": "./extension/my_subscriber.js", "type": "staticSubscriber", - "metadata": [ - { - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:common_event_config", - } - ], + "metadata": [{ + "name": "ohos.extability.staticSubscriber", + "resource": "$profile:common_event_config", + }], } ] ``` #### Internal Structure of the distroFilter Attribute -Application distribution rules. +Distribution rules of the application. -This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when AppGallery distributes applications. Applications can be distributed by API version, screen shape, or screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. +This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when AppGallery distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. -Table 15 Internal structure of the distroFilter attribute +Table 16 Internal structure of the distroFilter attribute | Attribute | Description | Data Type| Initial Value Allowed | | ------------- | ------------------------------------------------------------ | -------- | -------------------------- | | apiVersion | Supported API versions. For details, see Table 16. | Object array| Yes (initial value: left empty)| | screenShape | Supported screen shapes. | Object array| Yes (initial value: left empty)| -| screenWindow | Supported window resolutions when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)| -| screenDensity | Dots per inch (DPI) of the screen. This attribute is optional. The value options are as follows:
**sdpi**: small-scale dots per inch. This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: medium-scale dots per inch. This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: large-scale dots per inch. This value is applicable for devices with a DPI in the (160, 240] range.
**xldpi**: extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (240, 320] range.
**xxldpi**: extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI in the (320, 480] range.
**xxxldpi**: extra-extra-extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (480, 640] range.| Object array| Yes (initial value: left empty)| -| countryCode | Code of the country or region to which an application is to be distributed. For details, see ISO-3166-1. Enumerated definitions of multiple countries and regions are supported. This attribute is optional. The substring of the value consists of two uppercase letters and indicates the supported countries or regions.| Object array| Yes (initial value: left empty)| +| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)| +| screenDensity | Pixel density of the screen, in dots per inch (dpi). This attribute is optional. The value options are as follows:
**sdpi**: small-scale dots per inch. This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: medium-scale dots per inch. This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: large-scale dots per inch. This value is applicable for devices with a DPI in the (160, 240] range.
**xldpi**: extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (240, 320] range.
**xxldpi**: extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI in the (320, 480] range.
**xxxldpi**: extra-extra-extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (480, 640] range.| Object array| Yes (initial value: left empty)| +| countryCode | Code of the country or region to which the application is to be distributed. For details, see ISO-3166-1. Enumerated definitions of multiple countries and regions are supported. This attribute is optional. The substring of the value consists of two uppercase letters and indicates the supported countries or regions.| Object array| Yes (initial value: left empty)| -Table 16 Internal structure of the apiVersion attribute +Table 17 Internal structure of the apiVersion attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released. | Array | Yes (initial value: left empty)| +| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| -Table 17 Internal structure of the screenShape attribute +Table 18 Internal structure of the screenShape attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | The value can be **circle** or **rect**. Example: Different HAPs can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| +| value | The value can be **circle** or **rect**. Example: Different HAP files can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| -Table 18 Internal structure of the screenWindow attribute +Table 19 Internal structure of the screenWindow attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| | value | Width and height of the screen. The value is in the "width * height" format, in pixels, for example, **454*454**.| Array | Yes (initial value: left empty)| -Table 19 Internal structure of the screenDensity attribute +Table 20 Internal structure of the screenDensity attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Dots per inch (DPI) of the screen. | Array | Yes (initial value: left empty)| +| value | Pixel density of the screen, in dots per inch (dpi). | Array | Yes (initial value: left empty)| -Table 20 Internal structure of the countryCode attribute +Table 21 Internal structure of the countryCode attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Code of the country or region to which an application is to be distributed. | Array | Yes (initial value: left empty)| +| value | Code of the country or region to which the application is to be distributed. | Array | Yes (initial value: left empty)| Example of the **distroFilter** attribute structure: @@ -780,37 +794,50 @@ Define the **distroFilter_config.json** file in **resources/base/profile** of th ```json "distroFilter": [ { - "apiVersion": { + "apiVersion": { "policy": "include", - "value": [4,5] + "value": [4, 5] }, "screenShape": { "policy": "include", - "value": ["circle","rect"] + "value": ["circle", "rect"] }, "screenWindow": { "policy": "include", - "value": ["454*454","466*466"] + "value": ["454*454", "466*466"] } } ] ``` -Define the **metadata** information under **extensionAbilities** in the **module.json** file as follows: +Define the **metadata** information under **extensionAbilities** in the **module.json5** file as follows: ```json "extensionAbilities": [ { "name": "mySubscriber", "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [ - { - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:distroFilter_config", - } - ], + "type": "staticSubscriber", + "metadata": [{ + "name": "ohos.extability.staticSubscriber", + "resource": "$profile:distroFilter_config", + }], } ] +``` + +#### Internal Structure of the testRunner Attribute +Table 22 Internal structure of the testRunner attribute + +| Attribute| Description | Data Type| Initial Value Allowed| +| -------- | ---------------------- | -------- | ---------- | +| name | Name of the test runner object.| String | No| +| srcPath | Path of the test runner code.| String | No| + +``` +"testRunner": { + "name": "myTestRUnnerName", + "srcPath": "etc/test/TestRunner.ts" +} ``` diff --git a/en/application-dev/quick-start/syscap.md b/en/application-dev/quick-start/syscap.md index 1df5e3c82b4d6e97af1069d65b93336d84788cb4..07570f1359d7a4ead492ea15e02624f35e4e12c1 100644 --- a/en/application-dev/quick-start/syscap.md +++ b/en/application-dev/quick-start/syscap.md @@ -8,6 +8,10 @@ SysCap is short for System Capability. It refers to a standalone feature in the ![image-20220326064841782](figures/image-20220326064841782.png) +For details about the SysCap sets in OpenHarmony, see [SysCap List](../reference/syscap-list.md). + + + ### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps. @@ -60,14 +64,14 @@ You can add APIs to the associated SysCap set in DevEco Studio by adding system Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device. ```json -/* syscap.json */ +// syscap.json { "devices": { - "general": [ /* General devices. Each general device supports a SysCap set. Multiple general devices can be configured. */ + "general": [ // General devices. Each general device supports a SysCap set. Multiple general devices can be configured. "default", "car" ], - "custom": [ /* Custom devices. */ + "custom": [ // Custom devices. { "Custom device": [ "SystemCapability.Communication.SoftBus.Core" @@ -75,12 +79,12 @@ Exercise caution when modifying the required SysCap set. Incorrect modifications } ] }, - "development": { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */ + "development": { // The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. "addedSysCaps": [ "SystemCapability.Location.Location.Lite" ] }, - "production": { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ + "production": { // Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. "addedSysCaps": [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set. "removedSysCaps": [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device. } diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 2326ebb9436384c4476c2b834e9ea8c58533d1e7..e5e4ee0ea6213711aa17f1458385298f545d454e 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -1,8 +1,8 @@ # Development References - -- [Component Reference (TypeScript-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) -- [Component Reference (JavaScript-based Web-like Development Paradigm)](arkui-js/Readme-EN.md) -- [API Reference (JS and TS APIs)](apis/Readme-EN.md) -- API Reference (Native APIs) - - [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md) +- [SysCap List](syscap-list.md) +- [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) +- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md) +- [API Reference (JS and TS APIs)](apis/Readme-EN.md) +- API Reference (Native APIs) + - [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index e580b6bbef7bd71869de1da19a3a3d5c4757370d..1446d4fcef22eb94e6c4796be4e55fd0968c8e69 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,9 +1,7 @@ # APIs - [API Reference Document Description](development-intro.md) - - Ability Framework - - FA Model - [@ohos.ability.featureAbility](js-apis-featureAbility.md) - [@ohos.ability.particleAbility](js-apis-particleAbility.md) @@ -28,8 +26,6 @@ - application/[FormExtensionContext](js-apis-formextensioncontext.md) - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md) - - [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md) - - [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) - FA and Stage Models - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) @@ -60,18 +56,15 @@ - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - application/[ProcessRunningInfo](js-apis-processrunninginfo.md) + - application/[ProcessRunningInformation](js-apis-processrunninginformation.md) - application/[shellCmdResult](js-apis-application-shellCmdResult.md) - continuation/[ContinuationResult](js-apis-continuation-continuationResult.md) - Common Event and Notification - - [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.events.emitter](js-apis-emitter.md) - [@ohos.notification](js-apis-notification.md) - - [@ohos.reminderAgent](js-apis-reminderAgent.md) - application/[EventHub](js-apis-eventhub.md) - -- Bundle Management - + - Bundle Management - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) - [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) @@ -92,17 +85,14 @@ - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) - bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - - bundle/[ShortcutInfo](js-apis-bundle-ShortcutInfo.md) + - bundle/[ShortcutInfo(deprecated)](js-apis-bundle-ShortcutInfo.md) + - bundle/[PackInfo](js-apis-bundle-PackInfo.md) - UI Page - - [@ohos.animator](js-apis-animator.md) - [@ohos.mediaquery](js-apis-mediaquery.md) - - [@ohos.prompt](js-apis-prompt.md) - [@ohos.router](js-apis-router.md) - [@ohos.uiAppearance](js-apis-uiappearance.md) - -- Graphics - + - Graphics - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - [@ohos.display ](js-apis-display.md) - [@ohos.effectKit](js-apis-effectKit.md) @@ -111,42 +101,31 @@ - [@ohos.window](js-apis-window.md) - [webgl](js-apis-webgl.md) - [webgl2](js-apis-webgl2.md) - - Media - - [@ohos.multimedia.audio](js-apis-audio.md) - [@ohos.multimedia.camera](js-apis-camera.md) - [@ohos.multimedia.image](js-apis-image.md) - [@ohos.multimedia.media](js-apis-media.md) - - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - - Resource Management - - [@ohos.i18n](js-apis-i18n.md) - [@ohos.intl](js-apis-intl.md) - [@ohos.resourceManager](js-apis-resource-manager.md) - -- Resource Scheduling - +- Resource Scheduling - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.distributedMissionManager](js-apis-distributedMissionManager.md) - [@ohos.workScheduler ](js-apis-workScheduler.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - - Custom Management - - [@ohos.configPolicy](js-apis-config-policy.md) - - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - enterpriseDeviceManager/[DeviceSettingsManager](js-apis-enterpriseDeviceManager-DeviceSettingsManager.md) - - Security - - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager](js-apis-privacyManager.md) - [@ohos.security.huks ](js-apis-huks.md) - - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) + - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@system.cipher](js-apis-system-cipher.md) - Data Management @@ -155,7 +134,6 @@ - [@ohos.data.dataShare](js-apis-data-dataShare.md) - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - - [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.rdb](js-apis-data-rdb.md) @@ -167,46 +145,44 @@ - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) - [@ohos.fileio](js-apis-fileio.md) - - [@ohos.fileManager](js-apis-filemanager.md) + - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) + - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) - [@ohos.storageStatistics](js-apis-storage-statistics.md) - [@ohos.volumeManager](js-apis-volumemanager.md) - - [@ohos.securityLabel](js-apis-securityLabel.md) - - Telephony Service - - [@ohos.contact](js-apis-contact.md) - [@ohos.telephony.call](js-apis-call.md) + - [@ohos.telephony.data](js-apis-telephony-data.md) - [@ohos.telephony.observer](js-apis-observer.md) - [@ohos.telephony.radio](js-apis-radio.md) - [@ohos.telephony.sim](js-apis-sim.md) - [@ohos.telephony.sms](js-apis-sms.md) - - [@ohos.telephony.data](js-apis-telephony-data.md) - - Network Management - - [@ohos.net.connection](js-apis-net-connection.md) + - [@ohos.net.ethernet](js-apis-net-ethernet.md) - [@ohos.net.http](js-apis-http.md) - - [@ohos.request](js-apis-request.md) + - [@ohos.net.policy](js-apis-net-policy.md) + - [@ohos.net.sharing](js-apis-net-sharing.md) - [@ohos.net.socket](js-apis-socket.md) + - [@ohos.net.statistics](js-apis-net-statistics.md) + - [@ohos.net.tlsSocket](js-apis-tlsSocket.md) - [@ohos.net.webSocket](js-apis-webSocket.md) - + - [@ohos.request](js-apis-request.md) - Connectivity - - [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.connectedTag](js-apis-connectedTag.md) - [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md) - [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.tag](js-apis-nfcTag.md) - - [@ohos.nfc.tag](js-apis-nfctech.md) - - [@ohos.nfc.tag](js-apis-tagSession.md) - [@ohos.rpc](js-apis-rpc.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - + - tag/[nfctech](js-apis-nfctech.md) + - tag/[tagSession](js-apis-tagSession.md) - Basic Features - - [@ohos.accessibility](js-apis-accessibility.md) + - [@ohos.accessibility.config](js-apis-accessibility-config.md) - [@ohos.faultLogger](js-apis-faultLogger.md) - [@ohos.hiAppEvent](js-apis-hiappevent.md) - [@ohos.hichecker](js-apis-hichecker.md) @@ -217,13 +193,16 @@ - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - [@ohos.inputMethod](js-apis-inputmethod.md) - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) + - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) - [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.wallpaper](js-apis-wallpaper.md) + - [console](js-apis-logs.md) - [Timer](js-apis-timer.md) - + - Device Management - [@ohos.batteryInfo ](js-apis-battery-info.md) @@ -239,6 +218,7 @@ - [@ohos.multimodalInput.keyCode](js-apis-keycode.md) - [@ohos.multimodalInput.keyEvent](js-apis-keyevent.md) - [@ohos.multimodalInput.mouseEvent](js-apis-mouseevent.md) + - [@ohos.multimodalInput.pointer](js-apis-pointer.md) - [@ohos.multimodalInput.touchEvent](js-apis-touchevent.md) - [@ohos.power](js-apis-power.md) - [@ohos.runningLock](js-apis-runninglock.md) @@ -249,15 +229,12 @@ - [@ohos.update](js-apis-update.md) - [@ohos.usb](js-apis-usb.md) - [@ohos.vibrator](js-apis-vibrator.md) - -- Account Management - +- Account Management - [@ohos.account.appAccount](js-apis-appAccount.md) - [@ohos.account.distributedAccount](js-apis-distributed-account.md) - [@ohos.account.osAccount](js-apis-osAccount.md) - -- Language Base Class Library - + - Language Base Class Library + - [@ohos.buffer](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.process](js-apis-process.md) - [@ohos.uri](js-apis-uri.md) @@ -279,16 +256,15 @@ - [@ohos.util.Vector](js-apis-vector.md) - [@ohos.worker](js-apis-worker.md) - [@ohos.xml](js-apis-xml.md) - - Test - - [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.uitest](js-apis-uitest.md) - -- APIs No Longer Maintained - +- APIs No Longer Maintained - [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.data.storage](js-apis-data-storage.md) + - [@ohos.data.distributedData](js-apis-distributed-data.md) + - [@ohos.prompt](js-apis-prompt.md) + - [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@system.app](js-apis-system-app.md) - [@system.battery](js-apis-system-battery.md) - [@system.bluetooth](js-apis-system-bluetooth.md) @@ -308,4 +284,3 @@ - [@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_ExtensionContext_Example.png b/en/application-dev/reference/apis/figures/en_us_image_ExtensionContext_Example.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9314b00afe2cbb7534f7aefe0dc3d2499284bb Binary files /dev/null and b/en/application-dev/reference/apis/figures/en_us_image_ExtensionContext_Example.png differ diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index e487baedfd496a9ac0a6e90332aa99f3323a4fc2..ca3b0873ab187379e62b7640c55bb650f84d4850 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -139,6 +139,80 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { }) ``` +## bundle.getApplicationInfoSync9+ + +getApplicationInfoSync(bundleName: string, bundleFlags: number, userId: number): ApplicationInfo; + +Obtains the application information of the specified user based on a given bundle name. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| 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. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------- | +| [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | **ApplicationInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 0; +let userId = 100; +var applicationInfo = bundle.getApplicationInfoSync(bundleName, bundleFlags, userId); +console.info('Operation successful. Name:' + applicationInfo.name); +``` + +## bundle.getApplicationInfoSync9+ + +getApplicationInfoSync(bundleName: string, bundleFlags: number) : ApplicationInfo; + +Obtains the application information based on a given bundle name. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------- | +| [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | **ApplicationInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 0; +var applicationInfo = bundle.getApplicationInfoSync(bundleName, bundleFlags); +console.info('Operation successful. Name:' + applicationInfo.name); +``` + ## bundle.getAllBundleInfo getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> @@ -370,6 +444,82 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { }) ``` +## bundle.getBundleInfoSync9+ + +getBundleInfoSync(bundleName: string, bundleFlags: number, options: BundleOptions): BundleInfo; + +Obtains the bundle information based on a given bundle name and bundle options. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| options | [BundleOptions](#bundleoptions) | Yes | Options of the bundle. | + +**Return value** + +| Type | Description | +| ------------------------------------------ | -------------- | +| [BundleInfo](js-apis-bundle-BundleInfo.md) | **BundleInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 1; +let options = { + "userId" : 100 +}; +var bundleInfo = bundle.getBundleInfoSync(bundleName, bundleFlags, options); +console.info('Operation successful. Name:' + bundleInfo.name); +``` + +## bundle.getBundleInfoSync9+ + +getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo; + +Obtains the bundle information based on a given bundle name. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| + +**Return value** + +| Type | Description | +| ------------------------------------------ | -------------- | +| [BundleInfo](js-apis-bundle-BundleInfo.md) | **BundleInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 1; +var bundleInfo = bundle.getBundleInfoSync(bundleName, bundleFlags); +console.info('Operation successful. Name:' + bundleInfo.name); +``` + ## bundle.getBundleInstaller getBundleInstaller(): Promise<BundleInstaller>; @@ -685,7 +835,7 @@ This is a system API and cannot be called by third-party applications. | ----------- | --------------------------- | ---- | ---------------------- | | bundleName | string | Yes | Bundle name of an application. | | moduleName | string | Yes | Module name of the application. | -| upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| +| upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| **Return value** @@ -758,10 +908,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ---------------------------------- | ---- | ---------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package. | | callback | AsyncCallback | Yes | Callback used to return the bundle package information.| ## bundle.getBundlePackInfo9+ @@ -780,16 +930,16 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------------------- | ---- | ---------------------- | +| bundleName | string | Yes | Bundle name of an application. | | bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package.| **Return value** -| Type | Description | -| ---------------------------- | ----------------------------------- | -| Promise | Promise used to return the bundle package information.| +| Type | Description | +| ---------------------------- | ------------------------------------------------------ | +| Promise | Promise used to return the bundle package information. | ## bundle.getDispatcherVersion9+ @@ -1894,7 +2044,7 @@ SystemCapability.BundleManager.BundleFramework | -------------- | ------ | ---- | ---------------------------------------- | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | | extensionType | number | Yes | Type of the Extension ability information to obtain. The default value is **0**. For details on the available enumerated values, see [ExtensionAbilityType](#extensionabilitytype9).| -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| +| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| | 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** @@ -1943,7 +2093,7 @@ SystemCapability.BundleManager.BundleFramework | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | | extensionType | number | Yes | Type of the Extension ability information to obtain. The default value is **0**. For details on the available enumerated values, see [ExtensionAbilityType](#extensionabilitytype9).| -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| +| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| | 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. | @@ -1986,7 +2136,7 @@ SystemCapability.BundleManager.BundleFramework | -------------- | ---------------------------------------- | ---- | ---------------------------------------- | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | | extensionType | number | Yes | Type of the Extension ability information to obtain. The default value is **0**. For details on the available enumerated values, see [ExtensionAbilityType](#extensionabilitytype9).| -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| +| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| | callback | AsyncCallback> | Yes | Callback used to return the Extension ability information. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index dc2f0ef50ad05bc74b3e7ba301c421dfc3dae741..116af9c40bdb3c13cc278a13bb7ae5b08330095f 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -381,6 +381,53 @@ context.getDisplayOrientation().then((data) => { }); ``` +## Context.getExternalCacheDir + +getExternalCacheDir(callback: AsyncCallback\): void + +Obtains the external cache directory of the application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the absolute path of the cache directory.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getExternalCacheDir() +``` + +## Context.getExternalCacheDir + +getExternalCacheDir(): Promise\; + +Obtains the external cache directory of the application. 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 absolute path of the cache directory.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getExternalCacheDir().then((data) => { + console.info("=======================>getExternalCacheDirCallback====================>"); + console.info("====>data====>" + JSON.stringify(data)); +}); +``` + ## Context.setDisplayOrientation7+ setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index 06cac3878b46d62fdc09e6a342bdcc9340714c4f..7732457b6f32608db4c51f55e1cfa5ff0ee28ae8 100644 --- a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -49,3 +49,51 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil } }; ``` + +## EnterpriseAdminExtensionAbility.onBundleAdded + +onBundleAdded(bundleName: string): void + +Called when a bundle is added. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| bundleName | string | Yes | Name of the bundle added.| + +**Example** + +```ts +export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { + onBundleAdded(bundleName: string) { + console.log("added bundle name: " + bundleName); + } +}; +``` + +## EnterpriseAdminExtensionAbility.onBundleRemoved + +onBundleRemoved(bundleName: string): void + +Called when a bundle is removed. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| bundleName | string | Yes | Name of the bundle removed.| + +**Example** + +```ts +export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { + onBundleAdded(bundleName: string) { + console.log("removed bundle name: " + bundleName); + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index 9d33d34e9e0275c538e1cf2913af5fc0fdc656bc..4c173542ff27294e7d092576df392533af19222d 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -14,7 +14,7 @@ This module provides APIs for accessing ability-specific resources. You can use Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. ```js -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.application.Ability'; class MainAbility extends Ability { onWindowStageCreate(windowStage) { let context = this.context; @@ -34,7 +34,7 @@ class MainAbility extends Ability { ## AbilityContext.startAbility -startAbility(want: Want, callback: AsyncCallback<void>): void +startAbility(want: Want, callback: AsyncCallback<void>): void; Starts an ability. This API uses an asynchronous callback to return the result. @@ -63,9 +63,9 @@ Starts an ability. This API uses an asynchronous callback to return the result. ## AbilityContext.startAbility -startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void; -Starts an ability with start options specified. This API uses an asynchronous callback to return the result. +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1143,7 +1143,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call ## AbilityContext.setMissionLabel -setMissionLabel(label: string): Promise<void> +setMissionLabel(label: string): Promise<void>; Sets a label for this ability in the mission. This API uses a promise to return the result. @@ -1190,7 +1190,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call **Example** ```js - import image from '@ohos.multimedia.image' + import image from '@ohos.multimedia.image'; var imagePixelMap; var color = new ArrayBuffer(0); var initializationOptions = { @@ -1237,7 +1237,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return **Example** ```js - import image from '@ohos.multimedia.image' + import image from '@ohos.multimedia.image'; var imagePixelMap; var color = new ArrayBuffer(0); var initializationOptions = { diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 003a5efd92057dc7127b74aa35553f3220bd890e..733fee0c5671f9e100191f8b23a54fd7b5edec67 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -25,7 +25,7 @@ Creates an **AtManager** instance, which is used for ability access control. | Type| Description| | -------- | -------- | -| [AtManager](#atmanager) | **AtManager** instance obtained.| +| [AtManager](#atmanager) | **AtManager** instance created.| **Example** @@ -37,9 +37,9 @@ var AtManager = abilityAccessCtrl.createAtManager(); Implements ability access control. -### verifyAccessToken +### checkAccessToken9+ -verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> +checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> Checks whether an application has been granted the specified permission. This API uses a promise to return the result. @@ -49,24 +49,31 @@ Checks whether an application has been granted the specified permission. This AP | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to verify.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<GrantStatus> | Promise instance used to return the result.| +| Promise<GrantStatus> | Promise used to return the permission grant state.| **Example** ```js -var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; -let promise = AtManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + AtManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); + }).catch((err) => { + console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### verifyAccessTokenSync9+ @@ -81,7 +88,7 @@ Checks whether an application has been granted the specified permission. This AP | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. | | permissionName | string | Yes | Name of the permission to verify.| **Return value** @@ -95,13 +102,13 @@ Checks whether an application has been granted the specified permission. This AP ```js var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; -let data = verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let data = AtManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); console.log(`data->${JSON.stringify(data)}`); ``` ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> +grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> Grants a user granted permission to an application. This API uses a promise to return the result. @@ -115,31 +122,38 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to grant.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise instance used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** ```js -var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -let promise = AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + console.log('grantUserGrantedPermission success'); + }).catch((err) => { + console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void +grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. @@ -153,29 +167,35 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to grant.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<number> | Yes| Callback used to return the result.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js +import privacyManager from '@ohos.abilityAccessCtrl'; + var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { - if (err) { - console.log(`callback: err->${JSON.stringify(err)}`); - } else { - console.log(`callback: data->${JSON.stringify(data)}`); - } -}); +try { + AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (data, err) => { + if (err) { + console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('grantUserGrantedPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> +revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> Revokes a user granted permission given to an application. This API uses a promise to return the result. @@ -189,31 +209,38 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to revoke.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise instance used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** ```js -var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -let promise = AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + console.log('revokeUserGrantedPermission success'); + }).catch((err) => { + console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void +revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. @@ -227,24 +254,30 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to revoke.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<number> | Yes| Callback used to return the result.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js +import privacyManager from '@ohos.abilityAccessCtrl'; + var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { - if (err) { - console.log(`callback: err->${JSON.stringify(err)}`); - } else { - console.log(`callback: data->${JSON.stringify(data)}`); - } -}); +try { + AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (data, err) => { + if (err) { + console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('revokeUserGrantedPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### getPermissionFlags @@ -263,21 +296,167 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to query.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise instance used to return the result.| +| Promise<number> | Promise used to return the result.| + +**Example** + +```js +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let permissionFlag = 1; +try { + AtManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); + }).catch((err) = > { + console.log(`getPermissionFlags fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +### getVersion9+ + +getVersion(): Promise<number> + +Obtains the data version of the current permission management. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Security.AccessToken + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the version.| **Example** ```js var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; -let promise = AtManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let promise = AtManager.getVersion(); +promise.then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); +}); +``` + +### on9+ + +on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<string>, callback: Callback<PermissionStateChangeInfo>): void; + +Subscribes to permission grant state change events of a specified token ID list and permission list. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'permissionStateChange'**, indicating the permission grant state change event. | +| tokenIDList | Array<number> | No | List of token IDs. If this parameter is left empty, the permission grant state changes of all applications are subscribed to. | +| permissionNameList | Array<string> | No | List of permission names. If this parameter is left empty, the permission grant state changes of all permissions are subscribed to. | +| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | Yes| Callback used to return the permission grant state change information.| + +**Example** + +```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager = abilityAccessCtrl.createAtManager(); +let tokenIDList: Array = []; +let permissionNameList: Array = []; +try { + atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => { + console.debug("receive permission state change, data:" + JSON.stringify(data)); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +### off9+ + +off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<string>, callback?: Callback<PermissionStateChangeInfo>): void; + +Unsubscribes from permission grant state change events of a specified token ID list and permission list. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'permissionStateChange'**, indicating the permission grant state change event. | +| tokenIDList | Array<number> | No | List of token IDs. If this parameter is left empty, the permission grant state changes of all applications are unsubscribed from. The value must be the same as that passed in **on()**.| +| permissionNameList | Array<string> | No | List of permission names. If this parameter is left empty, the permission grant state changes of all permissions are unsubscribed from. The value must be the same as that passed in **on()**.| +| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | No| Callback used to return the permission grant state change information.| + +**Example** + +```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager = abilityAccessCtrl.createAtManager(); +let tokenIDList: Array = []; +let permissionNameList: Array = []; +try { + atManager.off('permissionStateChange', tokenIDList, permissionNameList); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +### verifyAccessToken(deprecated) + +verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> + +Checks whether an application has been granted the specified permission. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [checkAccessToken](#checkaccesstoken9) instead. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | +| permissionName | string | Yes | Name of the permission to verify.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<GrantStatus> | Promise used to return the permission grant state.| + +**Example** + +```js +import privacyManager from '@ohos.abilityAccessCtrl'; + +var AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let promise = AtManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); @@ -289,7 +468,34 @@ Enumerates the permission grant states. **System capability**: SystemCapability.Security.AccessToken -| Name | Default Value | Description | -| ----------------------------- | ---------------------- | ----------------------- | -| PERMISSION_DENIED | -1 | Permission denied. | -| PERMISSION_GRANTED | 0 | Permission granted. | +| Name | Default Value| Description | +| ------------------ | ----- | ----------- | +| PERMISSION_DENIED | -1 | Permission denied.| +| PERMISSION_GRANTED | 0 | Permission granted.| + +### PermissionStateChangeType9+ + +Enumerates the operations that trigger permission grant state changes. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Default Value| Description | +| ----------------------- | ------ | ----------------- | +| PERMISSION_REVOKED_OPER | 0 | Operation to revoke the permission.| +| PERMISSION_GRANTED_OPER | 1 | Operation to grant the permission.| + +### PermissionStateChangeInfo9+ + +Defines the detailed permission grant state change information. + +**System API**: This is a system API. + + **System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Readable| Writable| Description | +| -------------- | ------------------------- | ---- | ---- | ------------------ | +| change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | No | Operation that triggers the permission grant state change. | +| tokenID | number | Yes | No | Token ID of the application whose permission grant state changes are subscribed.| +| permissionName | string | Yes | No | Name of the permission whose grant state is changed.| diff --git a/en/application-dev/reference/apis/js-apis-accessibility-config.md b/en/application-dev/reference/apis/js-apis-accessibility-config.md new file mode 100644 index 0000000000000000000000000000000000000000..c33230f7181ce92a50cee6c1417eb5d71a124f68 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -0,0 +1,364 @@ +# System Accessibility Configuration + +The **config** module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + +## Modules to Import + +```typescript +import config from "@ohos.accessibility.config"; +``` + +## Attributes + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| highContrastText | [Config](#config)\| Yes| Yes| Whether to enable high-contrast text.| +| invertColor | [Config](#config)\| Yes| Yes| Whether to enable color inversion.| +| daltonizationColorFilter | [Config](#config)\<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Daltonization filter. | +| contentTimeout | [Config](#config)\| Yes| Yes| Recommended duration for content display. The value ranges from 0 to 5000, in milliseconds.| +| animationOff | [Config](#config)\| Yes| Yes| Whether to enable animation.| +| brightnessDiscount | [Config](#config)\| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.| +| mouseKey | [Config](#config)\| Yes| Yes| Whether to enable the mouse button feature.| +| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for the automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| +| shortkey | [Config](#config)\| Yes| Yes| Whether to enable the accessibility extension shortcut key.| +| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is bundleName/abilityName.| +| captions | [Config](#config)\| Yes| Yes| Whether to enable captions.| +| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](./js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| + +## enableAbility + +enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>): Promise<void>; + +Enables an accessibility extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>) | Yes| Capability of the accessibility extension ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + +**Example** + + ```typescript + config.enableAbility("com.ohos.example/axExtension", ['retrieve']) + .then(() => { + console.info('enable succeed'); + }).catch((error) => { + console.error('enable failed'); + }); + ``` + +## enableAbility + +enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>, callback: AsyncCallback<void>): void; + +Enables an accessibility extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +**Example** + + ```typescript + config.enableAbility("com.ohos.example/axExtension", ['retrieve'], (err, data) => { + if (err) { + console.error('enable failed'); + return; + } + console.info('enable succeed'); + }) + ``` + +## disableAbility + +disableAbility(name: string): Promise<void>; + +Disables an accessibility extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + +**Example** + + ```typescript + config.disableAbility("com.ohos.example/axExtension") + .then(() => { + console.info('disable succeed'); + }).catch((error) => { + console.error('disable failed'); + }); + ``` + +## disableAbility + +disableAbility(name: string, callback: AsyncCallback<void>): void; + +Disables an accessibility extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +**Example** + + ```typescript + config.disableAbility("com.ohos.example/axExtension", (err, data) => { + if (err) { + console.error('disable failed'); + return; + } + console.info('disable succeed'); + }) + ``` + +## on('enableAbilityListsStateChanged') + +on(type: 'enableAbilityListsStateChanged', callback: Callback<void>): void; + +Adds a listener for changes in the list of enabled accessibility extension abilities. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | +| callback | Callback<void> | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.| + +**Example** + + ```typescript + config.on('enableAbilityListsStateChanged',() => { + console.info('ax extension ability enable list changed'); + }); + ``` + +## off('enableAbilityListsStateChanged') + +off(type: 'enableAbilityListsStateChanged', callback?: Callback<void>): void; + +Cancels the listener for changes in the list of enabled accessibility extension abilities. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | +| callback | Callback<void> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| + +**Example** + + ```typescript + config.off('enableAbilityListsStateChanged'); + ``` + +## Config + +Implements configuration, acquisition, and listening for attributes. + +### set + +set(value: T): Promise<void>; + +Sets this attribute. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | T | Yes| Attribute value to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + +**Example** + + ```typescript + config.highContrastText.set(true) + .then(() => { + console.info('highContrastText set succeed'); + }).catch((error) => { + console.error('highContrastText set failed'); + }); + ``` + +### set + +set(value: T, callback: AsyncCallback<void>): void; + +Sets this attribute. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | T | Yes| Attribute value to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +**Example** + + ```typescript + config.highContrastText.set(true, (err, data) => { + if (err) { + console.error('highContrastText set failed'); + return; + } + console.info('highContrastText set succeed'); + }) + ``` + +### get + +get(): Promise<T>; + +Obtains the value of this attribute. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<T> | Promise used to return the attribute value.| + +**Example** + + ```typescript + config.highContrastText.get() + .then((value) => { + console.info('highContrastText get succeed'); + }).catch((error) => { + console.error('highContrastText get failed'); + }); + ``` + +### get + +get(callback: AsyncCallback<T>): void; + +Obtains the value of this attribute. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the attribute value.| + +**Example** + + ```typescript + config.highContrastText.get((err, data) => { + if (err) { + console.error('highContrastText get failed'); + return; + } + console.info('highContrastText get succeed'); + }) + ``` + +### on + +on(callback: Callback<T>): void; + +Adds a listener for attribute changes. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | Callback<T> | Yes| Callback invoked when the attribute changes.| + +**Example** + + ```typescript + config.highContrastText.on(() => { + console.info('highContrastText changed'); + }); + ``` + +### off + +off(callback?: Callback<T>): void; + +Cancels the listener for attribute changes. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | Callback<T> | No| Callback invoked when the attribute changes.| + +**Example** + + ```typescript + config.highContrastText.off(); + ``` + +## DaltonizationColorFilter + +Enumerates the daltonization filters. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name| Description| +| -------- | -------- | +| Normal | Filter for normal users.| +| Protanomaly | Filter for protanomaly.| +| Deuteranomaly | Filter for deuteranomaly.| +| Tritanomaly | Filter for tritanomaly.| diff --git a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md index 6a592ba663ec3723884fd0f44fef90a733230fa7..9fee7500eae2ec8435f0c3bdc2b48c986b14686a 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md @@ -34,13 +34,13 @@ Enumerates the focus directions. | up | Search for the next focusable item above the current item in focus.| | down | Search for the next focusable item below the current item in focus.| | left | Search for the next focusable item on the left of the current item in focus.| -| right | Search for the next focusable item on the right the current item in focus.| +| right | Search for the next focusable item on the right of the current item in focus.| | forward | Search for the next focusable item before the current item in focus.| | backward | Search for the next focusable item after the current item in focus.| ## FocusType -Enumerates of the focus types. +Enumerates the focus types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -55,8 +55,6 @@ Defines a rectangle. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - | Name | Type | Readable | Writable | Description | | ------ | ------ | ---- | ---- | --------- | | left | number | Yes | No | Left boundary of the rectangle.| @@ -75,35 +73,9 @@ Enumerates the window types. | application | Application window.| | system | System window.| -## AccessibilityExtensionContext.setEventTypeFilter - -setEventTypeFilter(type: Array): Promise\; - -Sets the concerned event type. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | ---- | -------- | -| type | Array<[EventType](js-apis-accessibility.md#EventType)> | Yes | Event type.| - -**Return value** - -| Type | Description | -| ---------------------- | --------------------- | -| Promise<boolean> | Promise used to return the result.| - -**Example** - -```ts -this.context.setEventTypeFilter(['click', 'longClick']); -``` - ## AccessibilityExtensionContext.setTargetBundleName -setTargetBundleName(targetNames: Array\): Promise\; +setTargetBundleName(targetNames: Array\): Promise\; Sets the concerned target bundle. @@ -139,7 +111,7 @@ Obtains the focus element. | Name | Type | Mandatory | Description | | -------------------- | ------- | ---- | ------------------- | -| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is false.| +| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| **Return value** @@ -213,7 +185,7 @@ this.context.getWindows().then(windows => { ## AccessibilityExtensionContext.injectGesture -injectGesture(gesturePath: GesturePath, listener: Callback\): Promise\): void Injects a gesture. @@ -224,13 +196,7 @@ Injects a gesture. | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | -------------- | | gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. | -| listener | Callback<boolean> | Yes | Callback used to return the result.| - -**Return value** - -| Type | Description | -| ---------------------- | ---------------------- | -| Promise<boolean> | Promise used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -244,3 +210,170 @@ this.context.gestureInject(gesturePath, (result) => { console.info('gestureInject result: ' + result); }) ``` +## AccessibilityElement.attributeNames + +attributeNames\(): Promise\>; + +Obtains all attribute names of this element. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<T>> | Promise used to return all attribute names of the element.| + +**Example** + +```ts +let accessibilityElement; +try { + accessibilityElement.attributeNames().then((values) => { + console.log("get attribute names success"); + }).catch((err) => { + console.log("get attribute names err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T): Promise\; + +Obtains the attribute value based on an attribute name. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<ElementAttributeValues[T]>> | Promise used to return the attribute value.| + +**Example** + +```ts +let accessibilityElement; +try { + let attributeName = 'name'; + accessibilityElement.attributeValue(attributeName).then((value) => { + console.log("get attribute value by name success"); + }).catch((err) => { + console.log("get attribute value by name err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.actionNames + +actionNames(): Promise\>; + +Obtains the names of all actions supported by this element. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<string>> | Promise used to return the names of all actions supported by the element.| + +**Example** + +```ts +let accessibilityElement; +try { + accessibilityElement.actionNames().then((values) => { + console.log("get action names success"); + }).catch((err) => { + console.log("get action names err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.performAction + +performAction(actionName: string, parameters?: object): Promise\; + +Performs an action based on the specified action name. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Action name. | +| parameters | object | No | Parameter required for performing the target action. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<boolean>> | Promise used to return the result.| + +**Example** + +```ts +let accessibilityElement; +try { + + accessibilityElement.performAction('action').then((result) => { + console.info('perform action result: ' + result); + }).catch((err) => { + console.log("perform action err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.findElement + +findElement(type: 'content', condition: string): Promise\>; + +Queries the information about this element based on the specified information type and condition. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'content'**. | +| condition | string | Yes | Search criteria. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<T>> | Promise used to return the result.| + +**Example** + +```ts +let accessibilityElement; +try { + let condition = 'keyword'; + accessibilityElement.findElement('content', condition).then((values) => { + console.log("find element success"); + }).catch((err) => { + console.log("find element err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md index c7a280fecc755160c7e7c602aed0f80e958fc9ee..7798cdee3d2f71f54e7cc6937816cbb4c253a833 100644 --- a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @@ -48,8 +48,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -94,8 +94,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -139,8 +139,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -181,8 +181,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -224,8 +224,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -269,8 +269,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { 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 c97515fa2bd988b91c4fd5c27a8e27ed285f141c..45024751e4460258a696e7f7e883e84fb93d73c2 100644 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @@ -14,19 +14,19 @@ The mission snapshot information can be obtained by using **getMissionSnapShot** ```js import ElementName from '@ohos.bundle'; import image from '@ohos.multimedia.image'; -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; +missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) + missionManager.getMissionSnapShot("", id, (error, snapshot) => { + console.log("getMissionSnapShot is called, error.code = " + error.code); + console.log("bundleName = " + snapshot.ability.bundleName); }) +}) ``` ## MissionSnapshot diff --git a/en/application-dev/reference/apis/js-apis-application-StartOptions.md b/en/application-dev/reference/apis/js-apis-application-StartOptions.md index d1d7416500d37ab61523633f3880670ad8b98779..39f44f65437b6b91ce457228fa12153d10aed3e6 100644 --- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md +++ b/en/application-dev/reference/apis/js-apis-application-StartOptions.md @@ -19,5 +19,5 @@ import StartOptions from '@ohos.application.StartOptions'; | Name| Readable| Writable| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#AbilityConstant.WindowMode) | Yes| No| number | No| Window mode.| +| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | Yes| No| number | No| Window mode.| | displayId | Yes| No| number | No| Display ID.| diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 9dc3ec0c3c5f022d4aecd438f59ebc830a34ae63..3d93bdf33a527668c4c1c98ac4cfd8611ea9010a 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -294,6 +294,9 @@ Registers an observer to listen for the state changes of all applications. }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -335,6 +338,9 @@ Registers an observer to listen for the state changes of a specified application }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } var bundleNameList = ['bundleName1', 'bundleName2']; @@ -707,6 +713,18 @@ Called when the application state changes. var applicationStateObserver = { onForegroundApplicationChanged(appStateData) { console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -734,8 +752,20 @@ Called when the ability state changes. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, onAbilityStateChanged(abilityStateData) { console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -762,8 +792,20 @@ Called when a process is created. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, onProcessCreated(processData) { console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -790,8 +832,20 @@ Called when a process is terminated. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -818,6 +872,18 @@ Called when the process state changes. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, onProcessStateChanged(processData) { console.log('------------ onProcessStateChanged -----------', processData); } diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 7fa4e76c7a448d1272d1a50b8da71e0303b27762..acd9ef20950cd35f4f25d0b63b5e33b4e4021e89 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -7,6 +7,7 @@ This module provides the following common audio-related functions: - [AudioManager](#audiomanager): audio management. - [AudioRenderer](#audiorenderer8): audio rendering, used to play Pulse Code Modulation (PCM) audio data. - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. +- [TonePlayer](#toneplayer9): tone player, used to manage and play Dual Tone Multi Frequency (DTMF) tones, such as dial tones and ringback tones. > **NOTE** > @@ -55,65 +56,11 @@ Obtains an **AudioManager** instance. var audioManager = audio.getAudioManager(); ``` -## audio.getStreamManager9+ - -getStreamManager(callback: AsyncCallback\): void - -Obtains an **AudioStreamManager** instance. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | Yes | **AudioStreamManager** instance.| - -**Example** - -```js -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - let audioStreamManager = data; - } -}); -``` - -## audio.getStreamManager9+ - -getStreamManager(): Promise - -Obtains an **AudioStreamManager** instance. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Core - -**Return value** - -| Type | Description | -| ---------------------------------------------------- | ---------------- | -| Promise<[AudioStreamManager](#audiostreammanager9)> | **AudioStreamManager** instance.| - -**Example** - -```js -var audioStreamManager; -audio.getStreamManager().then((data) => { - audioStreamManager = data; - console.info('getStreamManager: Success!'); -}).catch((err) => { - console.error(`getStreamManager: ERROR : ${err}`); -}); - -``` - ## audio.createAudioRenderer8+ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\): void -Obtains an **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +Creates an **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer @@ -160,7 +107,7 @@ audio.createAudioRenderer(audioRendererOptions,(err, data) => { createAudioRenderer(options: AudioRendererOptions): Promise -Obtains an **AudioRenderer** instance. This API uses a promise to return the result. +Creates an **AudioRenderer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer @@ -212,10 +159,12 @@ audio.createAudioRenderer(audioRendererOptions).then((data) => { createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback): void -Obtains an **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Creates an **AudioCapturer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.MICROPHONE + **Parameters** | Name | Type | Mandatory| Description | @@ -258,10 +207,12 @@ audio.createAudioCapturer(audioCapturerOptions, (err, data) => { createAudioCapturer(options: AudioCapturerOptions): Promise -Obtains an **AudioCapturer** instance. This API uses a promise to return the result. +Creates an **AudioCapturer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.MICROPHONE + **Parameters** | Name | Type | Mandatory| Description | @@ -305,6 +256,78 @@ audio.createAudioCapturer(audioCapturerOptions).then((data) => { }); ``` +## audio.createTonePlayer9+ + +createTonePlayer(options: AudioRendererInfo, callback: AsyncCallback<TonePlayer>): void + +Creates a **TonePlayer** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | -------------- | +| options | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| +| callback | AsyncCallback<[TonePlayer](#toneplayer9)> | Yes | Callback used to return the **TonePlayer** instance.| + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; + +var audioRendererInfo = { + "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags": 0 +} +var tonePlayer; + +audio.createTonePlayer(audioRendererInfo, (err, data) => { + console.info(`callback call createTonePlayer: audioRendererInfo: ${audioRendererInfo}`); + if (err) { + console.error(`callback call createTonePlayer return error: ${err.message}`); + } else { + console.info(`callback call createTonePlayer return data: ${data}`); + tonePlayer = data; + } +}); +``` + +## audio.createTonePlayer9+ + +createTonePlayer(options: AudioRendererInfo): Promise<TonePlayer> + +Creates a **TonePlayer** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory| Description | +| :------ | :---------------------------------------------| :--- | :----------- | +| options | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| + +**Return value** + +| Type | Description | +| ----------------------------------------- | -------------------------------- | +| Promise<[TonePlayer](#toneplayer9)> | Promise used to return the **TonePlayer** instance. | + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; +async function createTonePlayer(){ + var audioRendererInfo = { + "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags": 0 + } + let tonePlayer = await audio.createTonePlayer(this.audioRendererInfo); +} +``` + ## AudioVolumeType Enumerates the audio stream types. @@ -338,13 +361,13 @@ Enumerates the audio device flags. | Name | Default Value | Description | | ------------------------------- | ------ | ------------------------------------------------- | -| NONE_DEVICES_FLAG9+ | 0 | No flag.
This is a system API and cannot be called by third-party applications. | +| NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API and cannot be called by third-party applications. | | OUTPUT_DEVICES_FLAG | 1 | Output device.| | INPUT_DEVICES_FLAG | 2 | Input device.| | ALL_DEVICES_FLAG | 3 | All devices.| | DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | Distributed output device.
This is a system API and cannot be called by third-party applications. | | DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | Distributed input device.
This is a system API and cannot be called by third-party applications. | -| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output devices.
This is a system API and cannot be called by third-party applications. | +| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output device.
This is a system API and cannot be called by third-party applications. | ## DeviceRole @@ -479,12 +502,13 @@ Enumerates the audio stream usage. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | -| ---------------------------------- | ------ | ---------- | -| STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| -| STREAM_USAGE_MEDIA | 1 | Used for media. | -| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Used for voice communication.| -| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.| +| Name | Default Value| Description | +| ------------------------------------------| ------ | ---------- | +| STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| +| STREAM_USAGE_MEDIA | 1 | Used for media. | +| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Used for voice communication.| +| STREAM_USAGE_VOICE_ASSISTANT9+ | 3 | Used for voice assistant.| +| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.| ## FocusType9+ @@ -668,6 +692,8 @@ Describes the event received by the application when the volume is changed. Enumerates the types of connected devices. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Device | Name | Default Value| Description | @@ -689,7 +715,7 @@ Describes the volume group information. | groupId9+ | number | Yes | No | Group ID of the device.| | mappingId9+ | number | Yes | No | Group mapping ID.| | groupName9+ | number | Yes | No | Group name.| -| ConnectType9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| +| type9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| ## VolumeGroupInfos9+ @@ -761,11 +787,12 @@ Enumerates the audio source types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | -| :------------------------------ | :----- | :--------------------- | -| SOURCE_TYPE_INVALID | -1 | Invalid audio source. | -| SOURCE_TYPE_MIC | 0 | Mic source. | -| SOURCE_TYPE_VOICE_COMMUNICATION | 7 | Voice communication source.| +| Name | Default Value| Description | +| :------------------------------------------- | :----- | :--------------------- | +| SOURCE_TYPE_INVALID | -1 | Invalid audio source. | +| SOURCE_TYPE_MIC | 0 | Mic source. | +| SOURCE_TYPE_VOICE_RECOGNITION9+ | 1 | Voice recognition source. | +| SOURCE_TYPE_VOICE_COMMUNICATION | 7 | Voice communication source.| ## AudioScene8+ @@ -780,7 +807,6 @@ Enumerates the audio scenes. | AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API and cannot be called by third-party applications.| | AUDIO_SCENE_VOICE_CHAT | 3 | Voice chat audio scene. | - ## AudioManager Implements audio volume and audio device management. Before calling any API in **AudioManager**, you must use [getAudioManager](#audiogetaudiomanager) to create an **AudioManager** instance. @@ -801,7 +827,7 @@ Obtains an **AudioRoutingManager** instance. This API uses an asynchronous callb **Example** ```js -await audioManager.getRoutingManager((err, callback) => { +audioManager.getRoutingManager((err, callback) => { if (err) { console.error(`Result ERROR: ${err}`); } @@ -827,12 +853,15 @@ Obtains an **AudioRoutingManager** instance. This API uses a promise to return t **Example** ```js -await audioManager.getRoutingManager().then((value) => { - var routingManager = value; - console.info('getRoutingManager Promise SUCCESS.'); -}).catch((err) => { - console.error(`Result ERROR: ${err}`); -}); +var audioManager = audio.getAudioManager(); +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + var routingManager = value; + console.info('getRoutingManager Promise SUCCESS.'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` ### setVolume @@ -1951,6 +1980,7 @@ Sets an audio scene. This API uses an asynchronous callback to return the result **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { console.error(`Failed to set the audio scene mode.​ ${err}`); @@ -1985,6 +2015,7 @@ Sets an audio scene. This API uses a promise to return the result. **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { console.info('Promise returned to indicate a successful setting of the audio scene mode.'); }).catch ((err) => { @@ -2009,6 +2040,7 @@ Obtains the audio scene. This API uses an asynchronous callback to return the re **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getAudioScene((err, value) => { if (err) { console.error(`Failed to obtain the audio scene mode.​ ${err}`); @@ -2036,6 +2068,7 @@ Obtains the audio scene. This API uses a promise to return the result. **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getAudioScene().then((value) => { console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); }).catch ((err) => { @@ -2062,6 +2095,7 @@ Obtains the volume groups. This API uses an asynchronous callback to return the **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { console.error(`Failed to obtain the volume group infos list. ${err}`); @@ -2091,7 +2125,7 @@ Obtains the volume groups. This API uses a promise to return the result. | Type | Description | | ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information list.| +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| **Example** @@ -2116,12 +2150,14 @@ Obtains the audio group manager. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. | +| groupId | number | Yes | Volume group ID. | | callback | AsyncCallback< [AudioGroupManager](#audiogroupmanager9) > | Yes | Callback used to return the audio group manager.| **Example** ```js +var audioManager = audio.getAudioManager(); +var audioGroupManager; async function getGroupManager(){ let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); if (value.length > 0) { @@ -2151,8 +2187,8 @@ Obtains the audio group manager. This API uses a promise to return the result. **Parameters** | Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------- | ---- | -------------- -- | -| networkId | string | Yes | Network ID of the device. | +| ---------- | ---------------------------------------- | ---- | ---------------- | +| groupId | number | Yes | Volume group ID. | **Return value** @@ -2163,15 +2199,74 @@ Obtains the audio group manager. This API uses a promise to return the result. **Example** ```js +var audioManager = audio.getAudioManager(); async function getGroupManager(){ let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); if (value.length > 0) { let groupid = value[0].groupId; - let audioGroupManager = await audioManager.getGroupManager(audio.LOCAL_NETWORK_ID) + let audioGroupManager = await audioManager.getGroupManager(groupid) console.info('Callback invoked to indicate that the volume group infos list is obtained.'); } } ``` + +### getStreamManager9+ + +getStreamManager(callback: AsyncCallback\): void + +Obtains an **AudioStreamManager** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------- | +| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | Yes | **AudioStreamManager** instance.| + +**Example** + +```js +var audioManager = audio.getAudioManager(); +let audioStreamManager; +audioManager.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); +``` + +### getStreamManager9+ + +getStreamManager(): Promise + +Obtains an **AudioStreamManager** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ---------------- | +| Promise<[AudioStreamManager](#audiostreammanager9)> | **AudioStreamManager** instance.| + +**Example** + +```js +var audioManager = audio.getAudioManager(); +var audioStreamManager; +audioManager.getStreamManager().then((data) => { + audioStreamManager = data; + console.info('getStreamManager: Success!'); +}).catch((err) => { + console.error(`getStreamManager: ERROR : ${err}`); +}); + +``` + ### requestIndependentInterrupt9+ requestIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void @@ -2203,7 +2298,7 @@ async function requestIndependentInterrupt(){ ``` ### requestIndependentInterrupt9+ -requestIndependentInterrupt(focusType: FocusType: Promise +requestIndependentInterrupt(focusType: FocusType): Promise Requests independent interruption and obtains an interruption session ID. This API uses a promise to return the result. @@ -2265,7 +2360,7 @@ async function abandonIndependentInterrupt(){ ``` ### abandonIndependentInterrupt9+ -abandonIndependentInterrupt(focusType: FocusType]: Promise +abandonIndependentInterrupt(focusType: FocusType): Promise Abandons independent interruption. This API uses a promise to return the result. @@ -2313,6 +2408,8 @@ Sets the volume for a stream. This API uses an asynchronous callback to return t This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2345,6 +2442,8 @@ Sets the volume for a stream. This API uses a promise to return the result. This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2374,6 +2473,8 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): v Obtains the volume of a stream. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2401,6 +2502,8 @@ getVolume(volumeType: AudioVolumeType): Promise<number> Obtains the volume of a stream. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2429,6 +2532,8 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2456,6 +2561,8 @@ getMinVolume(volumeType: AudioVolumeType): Promise<number> Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2484,6 +2591,8 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2511,6 +2620,8 @@ getMaxVolume(volumeType: AudioVolumeType): Promise<number> Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2543,6 +2654,8 @@ Mutes or unmutes a stream. This API uses an asynchronous callback to return the This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2575,6 +2688,8 @@ Mutes or unmutes a stream. This API uses a promise to return the result. This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2604,6 +2719,8 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): voi Checks whether a stream is muted. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2631,6 +2748,8 @@ isMute(volumeType: AudioVolumeType): Promise<boolean> Checks whether a stream is muted. This method uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2655,7 +2774,7 @@ audioGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { ## AudioStreamManager9+ -Implements audio stream management. Before calling any API of **AudioStreamManager**, you must use **[getStreamManager](#audiogetstreammanager9)** to obtain an **AudioStreamManager** instance. +Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. ### getCurrentAudioRendererInfoArray9+ @@ -2674,16 +2793,6 @@ Obtains the information about the current audio renderers. This API uses an asyn **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); if (err) { @@ -2731,42 +2840,34 @@ Obtains the information about the current audio renderers. This API uses a promi **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); +async function getCurrentAudioRendererInfoArray(){ + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } } } - } -}).catch((err) => { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); -}); + }).catch((err) => { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + }); +} ``` ### getCurrentAudioCapturerInfoArray9+ @@ -2786,16 +2887,6 @@ Obtains the information about the current audio capturers. This API uses an asyn **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); if (err) { @@ -2841,40 +2932,32 @@ Obtains the information about the current audio capturers. This API uses a promi **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } +async function getCurrentAudioCapturerInfoArray(){ + await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } } - } -}).catch((err) => { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); -}); + }).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + }); +} ``` ### on('audioRendererChange')9+ @@ -2895,16 +2978,6 @@ Subscribes to audio renderer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; @@ -2946,16 +3019,6 @@ Unsubscribes from audio renderer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.off('audioRendererChange'); console.info('######### RendererChange Off is called #########'); ``` @@ -2978,19 +3041,9 @@ Subscribes to audio capturer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##'); + console.info(`## CapChange on is called for element ${i} ##`); console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); @@ -3028,23 +3081,13 @@ Unsubscribes from audio capturer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.off('audioCapturerChange'); console.info('######### CapturerChange Off is called #########'); ``` ## AudioRoutingManager9+ -Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to create an **AudioRoutingManager** instance. +Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. ### getDevices9+ @@ -3064,11 +3107,11 @@ Obtains the audio devices with a specific flag. This API uses an asynchronous ca **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } - else { + } else { AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { console.error(`Failed to obtain the device list. ${err}`); @@ -3103,6 +3146,7 @@ Obtains the audio devices with a specific flag. This API uses a promise to retur **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); @@ -3134,6 +3178,7 @@ Subscribes to device change events. When a device is connected or disconnected, **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); @@ -3162,29 +3207,113 @@ Unsubscribes from device change events. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ------------------------------------------ | | type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | | callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } - else { - AudioRoutingManager.off('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + } else { + AudioRoutingManager.off('deviceChange', (deviceChanged) => { console.info('Should be no callback.'); }); } }); ``` +### selectInputDevice9+ + +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void + +Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** +```js +var audioManager = audio.getAudioManager(); +let inputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select input devices result callback: SUCCESS'); } + }); + }); +} +``` + +### selectInputDevice9+ + +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> + +**System API**: This is a system API. + +Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | + +**Return value** + +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +var audioManager = audio.getAudioManager(); +let inputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Select input devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); + }); +} +``` + ### selectOutputDevice9+ selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -3199,21 +3328,25 @@ Selects an audio output device. Currently, only one output device can be selecte **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioDeviceDescriptor = [{ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, "networkId":audio.LOCAL_NETWORK_ID, "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices result callback: SUCCESS'); } + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); }); -}); +} ``` ### selectOutputDevice9+ @@ -3222,7 +3355,7 @@ selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void& **System API**: This is a system API. -Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Device @@ -3241,20 +3374,24 @@ Selects an audio output device. Currently, only one output device can be selecte **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioDeviceDescriptor =[{ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, "networkId":audio.LOCAL_NETWORK_ID, "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); }); -}); +} ``` ### selectOutputDeviceByFilter9+ @@ -3263,7 +3400,7 @@ selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: Audi **System API**: This is a system API. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Device @@ -3277,6 +3414,7 @@ Selects an audio output device based on the filter criteria. Currently, only one **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioRendererFilter = { "uid":20010041, "rendererInfo": { @@ -3290,15 +3428,18 @@ let outputAudioDeviceDescriptor = [{ "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices by filter result callback: SUCCESS'); } + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); }); -}); +} ``` ### selectOutputDeviceByFilter9+ @@ -3307,7 +3448,7 @@ selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: Audi **System API**: This is a system API. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Device @@ -3327,6 +3468,7 @@ Selects an audio output device based on the filter criteria. Currently, only one **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioRendererFilter = { "uid":20010041, "rendererInfo": { @@ -3340,14 +3482,17 @@ let outputAudioDeviceDescriptor = [{ "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices by filter result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }) -}); + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) + }); +} ``` ## AudioRendererChangeInfo9+ @@ -3356,12 +3501,12 @@ Describes the audio renderer change event. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable| Writable| Description | -| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API and cannot be called by third-party applications.| -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | -| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications.| +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API and cannot be called by third-party applications. | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | +| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. | ## AudioRendererChangeInfoArray9+ @@ -3375,26 +3520,19 @@ Describes the **AudioRenderChangeInfo** array, which is read-only. import audio from '@ohos.multimedia.audio'; var audioStreamManager; -var audioStreamManagerCB; var resultFlag = false; - -await audioManager.getStreamManager().then(async function (data) { - audioStreamManager = data; - console.info('Get AudioStream Manager : Success'); -}).catch((err) => { - console.error(`Get AudioStream Manager : ERROR : ${err}`); -}); +var audioManager = audio.getAudioManager(); audioManager.getStreamManager((err, data) => { if (err) { console.error(`Get AudioStream Manager : ERROR : ${err}`); } else { - audioStreamManagerCB = data; + audioStreamManager = data; console.info('Get AudioStream Manager : Success'); } }); -audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => { +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { console.info(`## RendererChange on is called for ${i} ##`); console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); @@ -3428,12 +3566,12 @@ Describes the audio capturer change event. **System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Readable| Writable| Description | -| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API and cannot be called by third-party applications.| -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | -| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications.| +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API and cannot be called by third-party applications. | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | +| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. | ## AudioCapturerChangeInfoArray9+ @@ -3447,6 +3585,16 @@ Describes the **AudioCapturerChangeInfo** array, which is read-only. import audio from '@ohos.multimedia.audio'; const audioManager = audio.getAudioManager(); +let audioStreamManager; +audioManager.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + var resultFlag = false; audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { @@ -3481,19 +3629,19 @@ Describes an audio device. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Readable| Writable| Description | -| ----------------------------- | -------------------------- | ---- | ---- | ---------- | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role.| -| deviceType | [DeviceType](#devicetype) | Yes | No | Device type.| -| id9+ | number | Yes | No | Device ID. | -| name9+ | string | Yes | No | Device name.| -| address9+ | string | Yes | No | Device address.| -| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates.| -| channelCounts9+ | Array<number> | Yes | No | Number of channels supported.| -| channelMasks9+ | Array<number> | Yes | No | Supported channel masks.| -| networkId9+ | string | Yes | No | ID of the device network.
This is a system API and cannot be called by third-party applications.| -| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API and cannot be called by third-party applications.| -| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API and cannot be called by third-party applications.| +| Name | Type | Readable | Writable | Description | +| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | +| id9+ | number | Yes | No | Device ID. | +| name9+ | string | Yes | No | Device name. | +| address9+ | string | Yes | No | Device address. | +| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | +| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | +| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | +| networkId9+ | string | Yes | No | ID of the device network.
This is a system API and cannot be called by third-party applications. | +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API and cannot be called by third-party applications. | +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API and cannot be called by third-party applications. | ## AudioDeviceDescriptors @@ -3529,13 +3677,11 @@ Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you m **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device - -| Name | Type | Mandatory | Description | -| -------------| ---------------------------------------- | ---- | -------------- | -| uid | number | Yes | Application ID.
System capability: SystemCapability.Multimedia.Audio.Core| -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
System capability: SystemCapability.Multimedia.Audio.Renderer| -| rendererId | number | No | Unique ID of an audio stream.
System capability: SystemCapability.Multimedia.Audio.Renderer| +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | **Example** @@ -3557,9 +3703,9 @@ Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable| Writable| Description | -| ----- | -------------------------- | ---- | ---- | ------------------ | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state.| +| Name | Type | Readable | Writable | Description | +| ------------------ | -------------------------- | -------- | -------- | --------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | **Example** @@ -3577,9 +3723,9 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------------------------------------- | :--- | :--------------------- | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information.| +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | **Example** @@ -3602,9 +3748,9 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Return value** -| Type | Description | -| -------------------------------------------------- | ------------------------------- | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information.| +| Type | Description | +| -------------------------------------------------- | ------------------------------------------------ | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | **Example** @@ -3629,9 +3775,9 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------------------------- | :--- | :------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** @@ -3655,9 +3801,9 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** @@ -3671,6 +3817,7 @@ audioRenderer.getStreamInfo().then((streamInfo) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### start8+ @@ -3683,9 +3830,9 @@ Starts the renderer. This API uses an asynchronous callback to return the result **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** @@ -3697,6 +3844,7 @@ audioRenderer.start((err) => { console.info('Renderer start success.'); } }); + ``` ### start8+ @@ -3709,9 +3857,9 @@ Starts the renderer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3721,6 +3869,7 @@ audioRenderer.start().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### pause8+ @@ -3733,9 +3882,9 @@ Pauses rendering. This API uses an asynchronous callback to return the result. **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** @@ -3747,6 +3896,7 @@ audioRenderer.pause((err) => { console.info('Renderer paused.'); } }); + ``` ### pause8+ @@ -3759,9 +3909,9 @@ Pauses rendering. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3771,6 +3921,7 @@ audioRenderer.pause().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### drain8+ @@ -3783,9 +3934,9 @@ Drains the playback buffer. This API uses an asynchronous callback to return the **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** @@ -3797,6 +3948,7 @@ audioRenderer.drain((err) => { console.info('Renderer drained.'); } }); + ``` ### drain8+ @@ -3809,9 +3961,9 @@ Drains the playback buffer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3821,6 +3973,7 @@ audioRenderer.drain().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### stop8+ @@ -3833,9 +3986,9 @@ Stops rendering. This API uses an asynchronous callback to return the result. **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** @@ -3847,6 +4000,7 @@ audioRenderer.stop((err) => { console.info('Renderer stopped.'); } }); + ``` ### stop8+ @@ -3859,9 +4013,9 @@ Stops rendering. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3871,6 +4025,7 @@ audioRenderer.stop().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### release8+ @@ -3883,9 +4038,9 @@ Releases the renderer. This API uses an asynchronous callback to return the resu **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** @@ -3897,6 +4052,7 @@ audioRenderer.release((err) => { console.info('Renderer released.'); } }); + ``` ### release8+ @@ -3909,9 +4065,9 @@ Releases the renderer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3921,6 +4077,7 @@ audioRenderer.release().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### write8+ @@ -3933,52 +4090,27 @@ Writes the buffer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | --------------------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; -import featureAbility from '@ohos.ability.featureAbility' - -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_2, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION - rendererFlags: 0 -} - -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -var audioRenderer; -audio.createAudioRenderer(audioRendererOptions).then((data)=> { - audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); - }); var bufferSize; audioRenderer.getBufferSize().then((data)=> { console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.error.(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); console.info(`Buffer size: ${bufferSize}`); var context = featureAbility.getContext(); -var path = await context.getCacheDir(); +var path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} var filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); @@ -3990,6 +4122,7 @@ audioRenderer.write(buf, (err, writtenbytes) => { console.info(`Actual written bytes: ${writtenbytes}`); } }); + ``` ### write8+ @@ -4002,41 +4135,13 @@ Writes the buffer. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; -import featureAbility from '@ohos.ability.featureAbility' - -var audioStreamInfo = { - samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels:audio.AudioChannel.CHANNEL_2, - sampleFormat:audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType:audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 0 -} - -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -var audioRenderer; -audio.createAudioRenderer(audioRendererOptions).then((data) => { - audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); - }); var bufferSize; audioRenderer.getBufferSize().then((data) => { console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); @@ -4046,8 +4151,11 @@ audioRenderer.getBufferSize().then((data) => { }); console.info(`BufferSize: ${bufferSize}`); var context = featureAbility.getContext(); -var path = await context.getCacheDir(); -var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; +var path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +var filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); @@ -4060,6 +4168,7 @@ audioRenderer.write(buf).then((writtenbytes) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### getAudioTime8+ @@ -4072,9 +4181,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the timestamp.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | **Example** @@ -4082,6 +4191,7 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioRenderer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); + ``` ### getAudioTime8+ @@ -4094,9 +4204,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Return value** -| Type | Description | -| ---------------- | ----------------------- | -| Promise\ | Promise used to return the timestamp.| +| Type | Description | +| ---------------- | ------------------------------------- | +| Promise\ | Promise used to return the timestamp. | **Example** @@ -4106,6 +4216,7 @@ audioRenderer.getAudioTime().then((timestamp) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### getBufferSize8+ @@ -4118,9 +4229,9 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the buffer size.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | **Example** @@ -4130,6 +4241,7 @@ var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { console.error('getBufferSize error'); } }); + ``` ### getBufferSize8+ @@ -4142,40 +4254,13 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Return value** -| Type | Description | -| ---------------- | --------------------------- | -| Promise\ | Promise used to return the buffer size.| +| Type | Description | +| ---------------- | --------------------------------------- | +| Promise\ | Promise used to return the buffer size. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; - -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_2, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 0 -} - -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -var audioRenderer; -audio.createAudioRenderer(audioRendererOptions).then((data) => { - audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); - }).catch((err) => { - console.info(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); - }); var bufferSize; audioRenderer.getBufferSize().then((data) => { console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); @@ -4183,6 +4268,7 @@ audioRenderer.getBufferSize().then((data) => { }).catch((err) => { console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); + ``` ### setRenderRate8+ @@ -4195,10 +4281,10 @@ Sets the render rate. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | ------------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ----------------------------------- | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -4210,6 +4296,7 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => console.info('Callback invoked to indicate a successful render rate setting.'); } }); + ``` ### setRenderRate8+ @@ -4222,15 +4309,15 @@ Sets the render rate. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------------------- | ---- | ------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate.| +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | --------- | ------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -4240,6 +4327,7 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### getRenderRate8+ @@ -4252,9 +4340,9 @@ Obtains the current render rate. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | **Example** @@ -4262,6 +4350,7 @@ Obtains the current render rate. This API uses an asynchronous callback to retur audioRenderer.getRenderRate((err, renderrate) => { console.info(`getRenderRate: ${renderrate}`); }); + ``` ### getRenderRate8+ @@ -4274,9 +4363,9 @@ Obtains the current render rate. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------------------------------------- | ------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate.| +| Type | Description | +| ------------------------------------------------- | --------------------------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | **Example** @@ -4286,7 +4375,9 @@ audioRenderer.getRenderRate().then((renderRate) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` + ### setInterruptMode9+ setInterruptMode(mode: InterruptMode): Promise<void> @@ -4297,42 +4388,28 @@ Sets the audio interruption mode for the application. This API uses a promise to **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------- | ------ | ---------- | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------ | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | **Return value** -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned.| +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | **Example** ```js -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_MUSIC, - usage: audio.StreamUsage.STREAM_USAGE_MEDIA, - rendererFlags: 0 -} -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 0; audioRenderer.setInterruptMode(mode).then(data=>{ console.info('setInterruptMode Success!'); }).catch((err) => { console.error(`setInterruptMode Fail: ${err}`); }); + ``` + ### setInterruptMode9+ setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void @@ -4343,30 +4420,14 @@ Sets the audio interruption mode for the application. This API uses a callback t **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ------ | -------------- | -|mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode.| -|callback | AsyncCallback\ | Yes |Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | --------- | ----------------------------------- | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_MUSIC, - usage: audio.StreamUsage.STREAM_USAGE_MEDIA, - rendererFlags: 0 -} -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 1; audioRenderer.setInterruptMode(mode, (err, data)=>{ if(err){ @@ -4374,7 +4435,9 @@ audioRenderer.setInterruptMode(mode, (err, data)=>{ } console.info('setInterruptMode Success!'); }); + ``` + ### on('interrupt')9+ on(type: 'interrupt', callback: Callback\): void @@ -4385,10 +4448,10 @@ Subscribes to audio interruption events. This API uses a callback to get interru **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.| -| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted. | +| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | **Example** @@ -4438,11 +4501,12 @@ audioRenderer.on('interrupt', async(interruptEvent) => { } } }); + ``` ### on('markReach')8+ -on(type: "markReach", frame: number, callback: Callback): void +on(type: "markReach", frame: number, callback: Callback<number>): void Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, the callback is invoked. @@ -4450,11 +4514,11 @@ Subscribes to mark reached events. When the number of frames rendered reaches th **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------- | :--- | :---------------------------------------- | -| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -4464,6 +4528,7 @@ audioRenderer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` @@ -4477,19 +4542,20 @@ Unsubscribes from mark reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **markReach**.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :----------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **markReach**. | **Example** ```js audioRenderer.off('markReach'); + ``` ### on('periodReach') 8+ -on(type: "periodReach", frame: number, callback: Callback): void +on(type: "periodReach", frame: number, callback: Callback<number>): void Subscribes to period reached events. When the period of frame rendering reaches the value of the **frame** parameter, the callback is invoked. @@ -4497,11 +4563,11 @@ Subscribes to period reached events. When the period of frame rendering reaches **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -4511,6 +4577,7 @@ audioRenderer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` ### off('periodReach') 8+ @@ -4523,14 +4590,15 @@ Unsubscribes from period reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :-------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **periodReach**.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **periodReach**. | **Example** ```js audioRenderer.off('periodReach') + ``` ### on('stateChange')8+ @@ -4543,10 +4611,10 @@ Subscribes to state change events. **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **stateChange** means the state change event.| -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** @@ -4559,6 +4627,7 @@ audioRenderer.on('stateChange', (state) => { console.info('audio renderer state is: STATE_RUNNING'); } }); + ``` ## AudioCapturer8+ @@ -4569,14 +4638,15 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo **System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Readable| Writable| Description | -| :---- | :------------------------- | :--- | :--- | :--------------- | -| state8+ | [AudioState](#audiostate8) | Yes| No | Audio capturer state.| +| Name | Type | Readable | Writable | Description | +| :----------------- | :------------------------- | :------- | :------- | :-------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | **Example** ```js var state = audioCapturer.state; + ``` ### getCapturerInfo8+ @@ -4589,9 +4659,9 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :-------------------------------- | :--- | :----------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the capturer information.| +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the capturer information. | **Example** @@ -4605,6 +4675,7 @@ audioCapturer.getCapturerInfo((err, capturerInfo) => { console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } }); + ``` @@ -4618,9 +4689,9 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Return value** -| Type | Description | -| :------------------------------------------------ | :---------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information.| +| Type | Description | +| :------------------------------------------------ | :----------------------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | **Example** @@ -4637,6 +4708,7 @@ audioCapturer.getCapturerInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); + ``` ### getStreamInfo8+ @@ -4649,9 +4721,9 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------------------------- | :--- | :------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** @@ -4667,6 +4739,7 @@ audioCapturer.getStreamInfo((err, streamInfo) => { console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } }); + ``` ### getStreamInfo8+ @@ -4679,9 +4752,9 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Return value** -| Type | Description | -| :--------------------------------------------- | :------------------------------ | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** @@ -4695,6 +4768,7 @@ audioCapturer.getStreamInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`getStreamInfo :ERROR: ${err}`); }); + ``` ### start8+ @@ -4707,9 +4781,9 @@ Starts capturing. This API uses an asynchronous callback to return the result. **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** @@ -4721,6 +4795,7 @@ audioCapturer.start((err) => { console.info('Capturer start success.'); } }); + ``` @@ -4734,35 +4809,13 @@ Starts capturing. This API uses a promise to return the result. **Return value** -| Type | Description | -| :------------- | :---------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; - -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_2, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 0 -} - -var audioCapturer; -audio.createAudioCapturer(audioCapturerOptions).then((data) => { - audioCapturer = data; - console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); - }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created: ERROR: ${err}`); - }); audioCapturer.start().then(() => { console.info('AudioFrameworkRecLog: ---------START---------'); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); @@ -4774,6 +4827,7 @@ audioCapturer.start().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); + ``` ### stop8+ @@ -4786,9 +4840,9 @@ Stops capturing. This API uses an asynchronous callback to return the result. **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** @@ -4800,6 +4854,7 @@ audioCapturer.stop((err) => { console.info('Capturer stopped.'); } }); + ``` @@ -4813,9 +4868,9 @@ Stops capturing. This API uses a promise to return the result. **Return value** -| Type | Description | -| :------------- | :---------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** @@ -4829,6 +4884,7 @@ audioCapturer.stop().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); + ``` ### release8+ @@ -4841,9 +4897,9 @@ Releases this **AudioCapturer** instance. This API uses an asynchronous callback **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** @@ -4855,6 +4911,7 @@ audioCapturer.release((err) => { console.info('capturer released.'); } }); + ``` @@ -4868,9 +4925,9 @@ Releases this **AudioCapturer** instance. This API uses a promise to return the **Return value** -| Type | Description | -| :------------- | :---------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** @@ -4884,6 +4941,7 @@ audioCapturer.release().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); + ``` @@ -4897,11 +4955,11 @@ Reads the buffer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| :------------- | :-------------------------- | :--- | :------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | -| callback | AsyncCallback | Yes | Callback used to return the buffer.| +| Name | Type | Mandatory | Description | +| :------------- | :-------------------------- | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer. | **Example** @@ -4918,6 +4976,7 @@ audioCapturer.read(bufferSize, true, async(err, buffer) => { console.info('Success in reading the buffer data'); } }); + ``` @@ -4931,16 +4990,16 @@ Reads the buffer. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| :------------- | :------ | :--- | :--------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation.| +| Name | Type | Mandatory | Description | +| :------------- | :------ | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------- | -| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned.| +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | **Example** @@ -4958,6 +5017,7 @@ audioCapturer.read(bufferSize, true).then((buffer) => { }).catch((err) => { console.info(`ERROR : ${err}`); }); + ``` @@ -4971,9 +5031,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **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** @@ -4981,6 +5041,7 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioCapturer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); + ``` @@ -4994,9 +5055,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Return value** -| Type | Description | -| :--------------- | :---------------------------- | -| Promise | Promise used to return the timestamp.| +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the timestamp. | **Example** @@ -5006,6 +5067,7 @@ audioCapturer.getAudioTime().then((audioTime) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); + ``` @@ -5019,9 +5081,9 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------- | :--- | :----------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size. | **Example** @@ -5036,6 +5098,7 @@ audioCapturer.getBufferSize((err, bufferSize) => { }); } }); + ``` @@ -5049,9 +5112,9 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Return value** -| Type | Description | -| :--------------- | :---------------------------------- | -| Promise | Promise used to return the buffer size.| +| Type | Description | +| :--------------- | :-------------------------------------- | +| Promise | Promise used to return the buffer size. | **Example** @@ -5063,12 +5126,13 @@ audioCapturer.getBufferSize().then((data) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); + ``` ### on('markReach')8+ -on(type: "markReach", frame: number, callback: Callback): void +on(type: "markReach", frame: number, callback: Callback<number>): void Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, the callback is invoked. @@ -5076,11 +5140,11 @@ Subscribes to mark reached events. When the number of frames captured reaches th **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :---------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered.| +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -5090,6 +5154,7 @@ audioCapturer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` ### off('markReach')8+ @@ -5102,19 +5167,20 @@ Unsubscribes from mark reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :-------------------------------------------- | -| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | **Example** ```js audioCapturer.off('markReach'); + ``` ### on('periodReach')8+ -on(type: "periodReach", frame: number, callback: Callback): void +on(type: "periodReach", frame: number, callback: Callback<number>): void Subscribes to mark reached events. When the period of frame capturing reaches the value of the **frame** parameter, the callback is invoked. @@ -5122,11 +5188,11 @@ Subscribes to mark reached events. When the period of frame capturing reaches th **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -5136,6 +5202,7 @@ audioCapturer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` ### off('periodReach')8+ @@ -5148,14 +5215,15 @@ Unsubscribes from period reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :---------------------------------------------- | -| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter. | **Example** ```js audioCapturer.off('periodReach') + ``` ### on('stateChange')8+ @@ -5168,10 +5236,10 @@ Subscribes to state change events. **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **stateChange** means the state change event.| -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** @@ -5184,4 +5252,262 @@ audioCapturer.on('stateChange', (state) => { console.info('audio capturer state is: STATE_RUNNING'); } }); + ``` + +## ToneType 9+ + +Enumerates the tone types of the player. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +| Name | Default Value | Description | +| :----------------------------------------------- | :------------ | :------------------------------------------- | +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | + +## TonePlayer9+ + +Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. + +### load9+ + +load(type: ToneType, callback: AsyncCallback<void>): void + +Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| type | ToneType(#tonetype9) | Yes | Tone type. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { + if (err) { + console.error(`callback call load failed error: ${err.message}`); + return; + } else { + console.info('callback call load success'); + } +}); + +``` + +### load9+ + +load(type: ToneType): Promise<void> + +Loads the DTMF tone configuration. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :------------------- | :-------- | ----------- | +| type | ToneType(#tonetype9) | Yes | Tone type. | + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { + console.info('promise call load '); +}).catch(() => { + console.error('promise call load fail'); +}); + +``` + +### start9+ + +start(callback: AsyncCallback<void>): void + +Starts DTMF tone playing. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.start((err) => { + if (err) { + console.error(`callback call start failed error: ${err.message}`); + return; + } else { + console.info('callback call start success'); + } +}); + +``` + +### start9+ + +start(): Promise<void> + +Starts DTMF tone playing. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.start().then(() => { + console.info('promise call start'); +}).catch(() => { + console.error('promise call start fail'); +}); + +``` + +### stop9+ + +stop(callback: AsyncCallback<void>): void + +Stops the tone that is being played. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.stop((err) => { + if (err) { + console.error(`callback call stop error: ${err.message}`); + return; + } else { + console.error('callback call stop success '); + } +}); + +``` + +### stop9+ + +stop(): Promise<void> + +Stops the tone that is being played. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.stop().then(() => { + console.info('promise call stop finish'); +}).catch(() => { + console.error('promise call stop fail'); +}); + +``` + +### release9+ + +release(callback: AsyncCallback<void>): void + +Releases the resources associated with the **TonePlay** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.release((err) => { + if (err) { + console.error(`callback call release failed error: ${err.message}`); + return; + } else { + console.info('callback call release success '); + } +}); +``` + +### release9+ + +release(): Promise<void> + +Releases the resources associated with the **TonePlay** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); +}); +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 67b4a955e1cfe2d9bd557cc47fdc938b010a8de6..d9f302b170e9fa953e1e06136c586ae53aa6ff46 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -2,15 +2,17 @@ The **BackgroundTaskManager** module provides APIs to manage background tasks. -If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. +If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension. If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup. If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task. -> **NOTE** +If a privileged system application needs to use certain system resources (for example, resources required to receive common events) when suspended, it can request efficiency resources. + +> **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 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -298,6 +300,64 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() ``` +## backgroundTaskManager.applyEfficiencyResources9+ + +applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest9)): boolean + +Requests efficiency resources from the system. +A process and its application can request the same type of resources at the same time, for example, CPU resources. When the application releases the resources, the same type of resources requested by the process are also released. + +**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ---------------------------------------- | +| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest9) | Yes | Necessary information carried in the request, including the resource type and timeout interval. For details, see [EfficiencyResourcesRequest](#efficiencyresourcesrequest9).| + +**Return value** +| Type | Description | +| -------------- | ---------------- | +| boolean | Returns **true** if the request for the resources is successful; returns **false** otherwise.| + +**Example** + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +let request = { + resourceTypes: backgroundTaskManager.ResourceType.CPU, + isApply: true, + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: false, +}; +let res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("result of applyEfficiencyResources is: " + res) +``` + +## backgroundTaskManager.resetAllEfficiencyResources9+ + +resetAllEfficiencyResources(): void + +Releases all resources that have been requested. + +**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply + +**System API**: This is a system API. + +**Example** + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); + +``` + ## DelaySuspendInfo Provides the information about the suspension delay. @@ -325,3 +385,38 @@ Provides the information about the suspension delay. | WIFI_INTERACTION | 7 | WLAN-related.
This is a system API.| | VOIP | 8 | Audio and video calls.
This is a system API. | | TASK_KEEPING | 9 | Computing task (effective only for specific devices). | + +## EfficiencyResourcesRequest9+ + +Describes the parameters for requesting efficiency resources. + +**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply + +**System API**: This is a system API. + +| Name | Type | Mandatory | Description | +| --------------- | ------ | ---- | ---------------------------------------- | +| resourceTypes | number | Yes | Type of the resource to request. | +| isApply | boolean | Yes | Whether the request is used to apply for resources. The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources. | +| timeOut | number | Yes | Duration for which the resource will be used, in milliseconds. | +| isPersist | boolean | No | Whether the resource is permanently held. If the value is **true**, **timeOut** is invalid. | +| isProcess | boolean | No | Whether the request is initiated by a process. The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. | +| reason | string | Yes | Reason for requesting the resource. | + +## ResourceType9+ + +Enumerates the efficiency resource types. + +**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply + +**System API**: This is a system API. + +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| CPU | 1 | CPU resources, which prevent the application from being suspended. | +| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. | +| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. | +| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | +| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | +| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | +| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 135400833c36005e1504b32f56f353cd2f271e40..2d7e9fab8a62e7d68dae92e66359a2704414bc01 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,6 +1,7 @@ # Battery Info ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** +> >The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. @@ -25,7 +26,7 @@ Describes battery information. | batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | | chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | | healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | -| pluggedType | [BatteryPluggedType](#batterypluggertype) | Yes | No | Charger type of the current device. | +| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | | voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | | technology | string | Yes | No | Battery technology of the current device. | | batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | @@ -43,12 +44,12 @@ var batterySoc = batteryInfo.batterySOC; Enumerates charger types. -| Name | Default Value | Description | -| -------- | ------------- | ---------------- | -| NONE | 0 | Unknown type | -| AC | 1 | AC charger | -| USB | 2 | USB charger | -| WIRELESS | 3 | Wireless charger | +| Name | Default Value | Description | +| -------- | ------------- | ----------------- | +| NONE | 0 | Unknown type. | +| AC | 1 | AC charger. | +| USB | 2 | USB charger. | +| WIRELESS | 3 | Wireless charger. | ## BatteryChargeState diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index eb54d689022397f603f9d93d2cc8591d9d1cdc82..b852a673ab6ca120497e1c40443d19990cfbd74b 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -223,7 +223,7 @@ cancelPairedDevice(deviceId: string): boolean Cancels a paired remote device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -389,7 +389,7 @@ startBluetoothDiscovery(): boolean Starts Bluetooth scan to discover remote devices. -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1293,7 +1293,7 @@ No value is returned. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let retArray = a2dpSrc.getConnectionDevices(); ``` @@ -1322,7 +1322,7 @@ Obtains the connection state of the profile. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); ``` @@ -1356,7 +1356,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); ``` @@ -1386,7 +1386,7 @@ Disconnects an A2DP connection. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1416,7 +1416,7 @@ No value is returned. function onReceiveEvent(data) { console.info('a2dp state = '+ JSON.stringify(data)); } -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; a2dpSrc.on('connectionStateChange', onReceiveEvent); ``` @@ -1446,7 +1446,7 @@ No value is returned. function onReceiveEvent(data) { console.info('a2dp state = '+ JSON.stringify(data)); } -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; a2dpSrc.on('connectionStateChange', onReceiveEvent); a2dpSrc.off('connectionStateChange', onReceiveEvent); ``` @@ -1475,7 +1475,7 @@ Obtains the playing state of a device. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); ``` @@ -1510,7 +1510,8 @@ Sets up a Hands-free Profile (HFP) connection of a device. **Example** ```js -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); ``` @@ -1540,7 +1541,8 @@ Disconnects the HFP connection of a device. **Example** ```js -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1570,7 +1572,8 @@ No value is returned. function onReceiveEvent(data) { console.info('hfp state = '+ JSON.stringify(data)); } -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; hfpAg.on('connectionStateChange', onReceiveEvent); ``` @@ -1600,7 +1603,8 @@ No value is returned. function onReceiveEvent(data) { console.info('hfp state = '+ JSON.stringify(data)); } -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; hfpAg.on('connectionStateChange', onReceiveEvent); hfpAg.off('connectionStateChange', onReceiveEvent); ``` @@ -1617,7 +1621,7 @@ connect(device: string): boolean Connects to the HidHost service of a device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -1638,7 +1642,7 @@ This is a system API. **Example** ```js -let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); ``` @@ -1649,7 +1653,7 @@ disconnect(device: string): boolean Disconnects from the HidHost service of a device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -1670,7 +1674,7 @@ This is a system API. **Example** ```js -let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1700,7 +1704,7 @@ No value is returned. function onReceiveEvent(data) { console.info('hidHost state = '+ JSON.stringify(data)); } -let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; hidHost.on('connectionStateChange', onReceiveEvent); ``` @@ -1730,7 +1734,7 @@ No value is returned. function onReceiveEvent(data) { console.info('hidHost state = '+ JSON.stringify(data)); } -let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; hidHost.on('connectionStateChange', onReceiveEvent); hidHost.off('connectionStateChange', onReceiveEvent); ``` @@ -1747,7 +1751,7 @@ disconnect(device: string): boolean Disconnects from the Personal Area Network (PAN) service of a device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -1768,7 +1772,7 @@ This is a system API. **Example** ```js -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1798,7 +1802,7 @@ No value is returned. function onReceiveEvent(data) { console.info('pan state = '+ JSON.stringify(data)); } -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; panProfile.on('connectionStateChange', onReceiveEvent); ``` @@ -1828,7 +1832,7 @@ No value is returned. function onReceiveEvent(data) { console.info('pan state = '+ JSON.stringify(data)); } -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; panProfile.on('connectionStateChange', onReceiveEvent); panProfile.off('connectionStateChange', onReceiveEvent); ``` @@ -1840,7 +1844,7 @@ setTethering(enable: boolean): void Sets tethering. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -1861,7 +1865,7 @@ This is a system API. **Example** ```js -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; let ret = panProfile.setTethering(true); ``` @@ -1872,7 +1876,7 @@ isTetheringOn(): boolean Obtains the tethering state. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1885,7 +1889,7 @@ This is a system API. **Example** ```js -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; let ret = panProfile.isTetheringOn(); ``` @@ -2217,7 +2221,7 @@ function ReadCharacteristicReq(CharacteristicReadReq) { let characteristicUuid = CharacteristicReadReq.characteristicUuid; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); @@ -2294,10 +2298,10 @@ function WriteCharacteristicReq(CharacteristicWriteReq) { let needRsp = CharacteristicWriteReq.needRsp; let value = new Uint8Array(CharacteristicWriteReq.value); let characteristicUuid = CharacteristicWriteReq.characteristicUuid; - + cccValue[0] = value[0]; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); @@ -2374,7 +2378,7 @@ function ReadDescriptorReq(DescriptorReadReq) { let descriptorUuid = DescriptorReadReq.descriptorUuid; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); @@ -2454,7 +2458,7 @@ function WriteDescriptorReq(DescriptorWriteReq) { descValue[0] = value[0]; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index b1c81e2eecd00b5043bb703b574bcc0c06533373..c055385384fc9c1a28818fc0a1bd23a355e83076 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -16,6 +16,16 @@ import buffer from '@ohos.buffer'; ## Buffer +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Length of the buffer, in bytes.| +| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| +| byteOffset | number | Yes| No| Offset of the buffer in the memory pool.| + ### alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer @@ -2422,7 +2432,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc let blob3 = blob.slice(0, 2, "MIME"); ``` - ### text +### text text(): Promise<string> diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index eb85e5d52d50068b8147c1a4789389b2cf5506e1..d744a5ab3e1ef6770d0dee18d68c4a1512cd4183 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,40 +1,40 @@ # BundleInfo +The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. + > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - ## BundleInfo **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Bundle name. | -| type | string | Yes | No | Bundle type. | -| appId | string | Yes | No | ID of the application to which the bundle belongs. | -| uid | number | Yes | No | UID of the application to which the bundle belongs. | -| installTime | number | Yes | No | Time when the HAP file was installed. | -| updateTime | number | Yes | No | Time when the HAP file was updated. | -| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | +| name | string | Yes | No | Bundle name. | +| type | string | Yes | No | Bundle type. | +| appId | string | Yes | No | ID of the application to which the bundle belongs. | +| uid | number | Yes | No | UID of the application to which the bundle belongs. | +| installTime | number | Yes | No | Time when the HAP file was installed. | +| updateTime | number | Yes | No | Time when the HAP file was updated. | +| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| | reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | -| versionName | string | Yes | No | Version description of the bundle. | -| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | -| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | -| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | -| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | +| vendor | string | Yes | No | Vendor of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | +| versionName | string | Yes | No | Version description of the bundle. | +| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | +| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | +| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | +| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | | extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.
The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.| @@ -45,8 +45,8 @@ Provides the detailed information of the permissions to request from the system. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------------------- | ----------------------- | ---- | ---- | -------------------- | +| Name | Type | Readable| Writable| Description | +| --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId9+ | number | Yes | Yes | ID of the reason for requesting the permission.| @@ -60,7 +60,7 @@ Describes the application scenario and timing for using the permission. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------- | -------------- | ---- | ---- | ------------------------- | +| Name | Type | Readable| Writable| Description | +| --------- | -------------- | ---- | ---- | --------------------------- | | abilities | Array\ | Yes | Yes | Abilities that use the permission.| | when | string | Yes | Yes | Time when the permission is used. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..323d4d1f948d12193b38333a11f7954153fec97a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md @@ -0,0 +1,157 @@ +# PackInfo + +The **PackInfo** module provides the bundle package information, which can be obtained using [bundle.getBundlePackInfo](js-apis-Bundle.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## BundlePackFlag + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Value | Description | +| ------------------ | ---------- | ---------------------------------- | +| GET_PACK_INFO_ALL | 0x00000000 | All information about the package. | +| GET_PACKAGES | 0x00000001 | Package information about the package.| +| GET_BUNDLE_SUMMARY | 0x00000002 | Bundle summary of the package. | +| GET_MODULE_SUMMARY | 0x00000004 | Module summary of the package. | + +## BundlePackInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------- | --------------------------------------- | ---- | ---- | ----------------------------- | +| packages | Array\<[PackageConfig](#packageconfig)> | Yes | No | Package configuration information. | +| summary | [PackageSummary](#packagesummary) | Yes | No | Package summary.| + +## PackageConfig + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| deviceType | Array\ | Yes | No | Device types supported. | +| name | string | Yes | No | Package name. | +| moduleType | string | Yes | No | Module type. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| + +## PackageSummary + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | --------------------------------------------- | ---- | ---- | -------------------- | +| app | [BundleConfigInfo](#bundleconfiginfo) | Yes | No | Bundle configuration information. | +| modules | Array\<[ModuleConfigInfo](#moduleconfiginfo)> | Yes | No | Module configuration information.| + +## BundleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ---------- | ------------------- | ---- | ---- | ---------------------------------- | +| bundleName | string | Yes | No | Bundle name of an application. It uniquely identifies the application.| +| version | [Version](#version) | Yes | No | Bundle version. | + +## ModuleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------ | ------------------------------------------------- | ---- | ---- | ---------------------------------- | +| apiVersion | [ApiVersion](#apiversion) | Yes | No | API version of the module. | +| deviceType | Array\ | Yes | No | Device type of the module. | +| distro | [ModuleDistroInfo](#moduledistroinfo) | Yes | No | Distribution information of the module. | +| abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | Yes | No | Ability information of the module. | +| extensionAbilities | Array\<[ExtensionAbilities](#extensionabilities)> | Yes | No | Extension ability information of the module.| + +## ModuleDistroInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | +| mainAbility | string | Yes | No | Name of the main ability. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| +| installationFree | boolean | Yes | No | Whether the HAP file supports the installation-free feature. The value **true** means that the HAP file supports the installation-free feature and meets installation-free constraints, and **false** means the opposite.| +| moduleName | string | Yes | No | Module name. | +| moduleType | string | Yes | No | Module type. | + +## ModuleAbilityInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Logical name of the ability. The name must be unique in the application. | +| label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.| +| visible | boolean | Yes | No | Whether the ability can be called by other applications. The value **true** means that the ability can be called by other applications, and **false** means the opposite.| +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. | + +## ExtensionAbilities + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Specification of the widget. A widget is a brief view of an application that is embedded on the home screen to receive periodical updates.| + +## AbilityFormInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Widget name. | +| type | string | Yes | No | Widget type. | +| updateEnabled | boolean | Yes | No | Whether the widget supports periodical update. The value **true** means that the widget supports periodical update, and **false** means the opposite.| +| scheduledUpdateTime | string | Yes | No | Scheduled time to update the widget. The value is in 24-hour format and accurate to the minute. | +| updateDuration | number | Yes | No | Interval to update the widget. The unit is 30 minutes. The value is a multiple of 30. A widget can be updated periodically, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). If both are configured, **updateDuration** takes precedence.| +| supportDimensions | Array\ | Yes | No | Dimensions of the widget. The value can be **1\*2**, **2\*2**, **2\*4**, **4\*4**, or a combination of these options. At least one option must be specified when defining the widget.| +| defaultDimension | number | Yes | No | Default dimensions of the widget. The value must be available in the **supportDimensions** array of the widget.| + +## ApiVersion + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | -------------------- | +| releaseType | string | Yes | No | Name of the API version. | +| compatible | number | Yes | No | Minimum API version.| +| target | numbe | Yes | No | Target API version. | + +## Version + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| minCompatibleVersionCode | number | Yes | No | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario. The value is a 32-bit non-negative integer.| +| name | string | Yes | No | Application version number visible to users. | +| code | number | Yes | No | Application version number used only for application management. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version.| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 9b20ccb9f359ed6f8109d3fc57fdebd9d4d728ed..ab561f552758ed5af3c79bc2c4406d84ceb56f2b 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -319,7 +319,7 @@ Checks whether the called number is an emergency number based on the specified p **Example** ```js -call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, value) => { +call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -468,9 +468,7 @@ The phone number must match the specified country code. For example, for a China **Example** ```js -call.formatPhoneNumberToE164("138xxxxxxxx",{ - countryCode: "CN" -}, (err, data) => { +call.formatPhoneNumberToE164("138xxxxxxxx", "CN", (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -504,9 +502,7 @@ All country codes are supported. **Example** ```js -let promise = call.formatPhoneNumberToE164("138xxxxxxxx", { - countryCode: "CN" -}); +let promise = call.formatPhoneNumberToE164("138xxxxxxxx", "CN"); promise.then(data => { console.log(`formatPhoneNumberToE164 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -831,7 +827,7 @@ call.reject(1, (error, data) => { ## call.reject7+ -reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback\): void +reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. @@ -1700,7 +1696,7 @@ This is a system API. **Example** ```js -isNewCallAllowedcall.on('mmiCodeResult', (err, data) => { +call.on('mmiCodeResult', (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2069,9 +2065,6 @@ This is a system API. **Example** ```js -let callTransferTyp={ - CallTransferType: 1 -} call.getCallTransferInfo(0, callTransferTyp, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -2104,10 +2097,7 @@ This is a system API. **Example** ```js -let callTransferTyp={ - CallTransferType: 1 -} -let promise = call.getCallTransferInfo(0, callTransferTyp); +let promise = call.getCallTransferInfo(0, call.CallTransferType.TRANSFER_TYPE_BUSY); promise.then(data => { console.log(`getCallTransferInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -2396,7 +2386,7 @@ This is a system API. let audioDeviceOptions={ bluetoothAddress: "IEEE 802-2014" } -call.setAudioDevice(1, bluetoothAddress, (err, value) => { +call.setAudioDevice(1, audioDeviceOptions, (err, value) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2460,7 +2450,10 @@ This is a system API. **Example** ```js -call.joinConference(1, "138XXXXXXXX", (err, data) => { +let callNumberList: Array = [ + "138XXXXXXXX" +]; +call.joinConference(1, callNumberList, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2491,7 +2484,10 @@ This is a system API. **Example** ```js -let promise = call.joinConference(1, "138XXXXXXXX"); +let callNumberList: Array = [ + "138XXXXXXXX" +]; +let promise = call.joinConference(1, callNumberList); promise.then(data => { console.log(`joinConference success, promise: data->${JSON.stringify(data)}`); }).catch(err => { diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 9168a42e978c20caaface2523337d8c413a2296e..b4f3906b02b1dea7dabd558173010a37e65c2c19 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,6 +1,6 @@ # Standard NFC Card Emulation -The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. +The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). > **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,6 +12,17 @@ The **cardEmulation** module implements Near-Field Communication (NFC) card emul import cardEmulation from '@ohos.nfc.cardEmulation'; ``` +## FeatureType + +Enumerates the NFC card emulation types. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| HCE | 0 | HCE.| +| UICC | 1 | Subscriber identity module (SIM) card emulation.| +| ESE | 2 | embedded Secure Element (eSE) emulation.| ## cardEmulation.isSupported @@ -19,23 +30,31 @@ isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ----------------------- | +| feature | number | Yes | Card emulation type. For details, see [FeatureType](#featuretype).| + **Return value** | **Type**| **Description**| | -------- | -------- | - | boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.| + | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ -Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance. +Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE. ### startHCE8+ startHCE(aidList: string[]): boolean -Starts HCE. +Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -45,13 +64,13 @@ Starts HCE. | Name | Type | Mandatory| Description | | ------- | -------- | ---- | ----------------------- | -| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| +| aidList | string[] | Yes | AID list to register.| ### stopHCE8+ stopHCE(): boolean -Stops HCE. +Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -61,7 +80,7 @@ Stops HCE. on(type: "hceCmd", callback: AsyncCallback): void; -Subscribes to messages from the peer device after **startHCE()**. +Registers a callback to receive APDUs from the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -72,13 +91,13 @@ Subscribes to messages from the peer device after **startHCE()**. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------------- | | type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | -| callback | AsyncCallback | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).| +| callback | AsyncCallback | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.| ### sendResponse8+ sendResponse(responseApdu: number[]): void; -Sends a response to the peer device. +Sends a response to the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -88,16 +107,25 @@ Sends a response to the peer device. | Name | Type | Mandatory| Description | | ------------ | -------- | ---- | -------------------------------------------------- | -| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.| +| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. Each number of the APDU is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js +import cardEmulation from '@ohos.nfc.cardEmulation'; + +var isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE); +if (!isHceSupported) { + console.log('this device is not supported for HCE, ignore it.'); + return; +} + +// The device supports HCE and transimits APDUs with the remote NFC reader. var hceService = new cardEmulation.HceService(); hceService.startHCE([ "F0010203040506", "A0000000041010" -]) -hceService.stopHCE(); +]); + hceService.on("hceCmd", (err, res) => { if(err.data === 0) { console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); @@ -108,4 +136,7 @@ hceService.on("hceCmd", (err, res) => { console.log('callback => Operation hceCmd failed. Cause: ' + err.data); } }) + +// Stop HCE when the application exits the NFC card emulation. +hceService.stopHCE(); ``` diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 50fad38058530104fda01f09d5745c0f8051000a..5aaacbe7d104cf965d398240ff8e19468644713b 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -18,7 +18,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v **System capability**: SystemCapability.Notification.CommonEvent -| Name | Value | Subscriber Permission | Description | +| Name | Value | Subscriber Permission | Description | | ------------ | ------------------ | ---------------------- | -------------------- | | COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | | COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | @@ -152,31 +152,32 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | | COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | | COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | -| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device becomes unmountable. | -| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | | COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | | COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | -| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | +| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | - | Indicates the common event of screen splitting. | | COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | | COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | +| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | ## CommonEvent.publish publish(event: string, callback: AsyncCallback\): void -Publishes a common event. This API uses a callback to return the result. +Publishes a common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -209,7 +210,7 @@ CommonEvent.publish("event", PublishCallBack); publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void -Publishes a common event with given attributes. This API uses a callback to return the result. +Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -226,7 +227,7 @@ Publishes a common event with given attributes. This API uses a callback to retu ```js // Attributes of a common event. -var options = { +let options = { code: 0, // Result code of the common event. data: "initial data";// Result data of the common event. isOrdered: true // The common event is an ordered one. @@ -251,7 +252,7 @@ CommonEvent.publish("event", options, PublishCallBack); publishAsUser(event: string, userId: number, callback: AsyncCallback\): void -Publishes a common event to a specific user. This API uses a callback to return the result. +Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -278,7 +279,7 @@ function PublishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); @@ -290,7 +291,7 @@ CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void -Publishes a common event with given attributes to a specific user. This API uses a callback to return the result. +Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -310,9 +311,9 @@ Publishes a common event with given attributes to a specific user. This API uses ```js // Attributes of a common event. -var options = { +let options = { code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event + data: "initial data";// Result data of the common event. } // Callback for common event publication @@ -325,7 +326,7 @@ function PublishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); @@ -337,7 +338,7 @@ CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void -Creates a subscriber. This API uses a callback to return the result. +Creates a subscriber. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -352,10 +353,10 @@ Creates a subscriber. This API uses a callback to return the result. ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -397,10 +398,10 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -419,7 +420,7 @@ CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void -Subscribes to common events. This API uses a callback to return the result. +Subscribes to common events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -433,10 +434,10 @@ Subscribes to common events. This API uses a callback to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -471,7 +472,7 @@ CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void -Unsubscribes from common events. This API uses a callback to return the result. +Unsubscribes from common events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -485,10 +486,10 @@ Unsubscribes from common events. This API uses a callback to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -535,7 +536,7 @@ CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); getCode(callback: AsyncCallback\): void -Obtains the result code of this common event. This API uses a callback to return the result. +Obtains the result code of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -548,7 +549,7 @@ Obtains the result code of this common event. This API uses a callback to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code obtaining of an ordered common event. function getCodeCallback(err, Code) { @@ -578,7 +579,7 @@ Obtains the result code of this common event. This API uses a promise to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getCode().then((Code) => { console.info("getCode " + JSON.stringify(Code)); @@ -591,7 +592,7 @@ subscriber.getCode().then((Code) => { setCode(code: number, callback: AsyncCallback\): void -Sets the result code for this common event. This API uses a callback to return the result. +Sets the result code for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -605,7 +606,7 @@ Sets the result code for this common event. This API uses a callback to return t **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code setting of an ordered common event. function setCodeCallback(err) { @@ -641,7 +642,7 @@ Sets the result code for this common event. This API uses a promise to return th **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCode(1).then(() => { console.info("setCode"); @@ -654,7 +655,7 @@ subscriber.setCode(1).then(() => { getData(callback: AsyncCallback\): void -Obtains the result data of this common event. This API uses a callback to return the result. +Obtains the result data of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -667,7 +668,7 @@ Obtains the result data of this common event. This API uses a callback to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result data obtaining of an ordered common event. function getDataCallback(err, Data) { @@ -697,7 +698,7 @@ Obtains the result data of this common event. This API uses a promise to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getData().then((Data) => { console.info("getData " + JSON.stringify(Data)); @@ -710,7 +711,7 @@ subscriber.getData().then((Data) => { setData(data: string, callback: AsyncCallback\): void -Sets the result data for this common event. This API uses a callback to return the result. +Sets the result data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -724,7 +725,7 @@ Sets the result data for this common event. This API uses a callback to return t **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result data setting of an ordered common event function setDataCallback(err) { @@ -760,7 +761,7 @@ Sets the result data for this common event. This API uses a promise to return th **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setData("publish_data_changed").then(() => { console.info("setData"); @@ -773,7 +774,7 @@ subscriber.setData("publish_data_changed").then(() => { setCodeAndData(code: number, data: string, callback:AsyncCallback\): void -Sets the result code and result data for this common event. This API uses a callback to return the result. +Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -788,7 +789,7 @@ Sets the result code and result data for this common event. This API uses a call **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code and result data setting of an ordered common event. function setCodeDataCallback(err) { @@ -825,7 +826,7 @@ Sets the result code and result data for this common event. This API uses a prom **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); @@ -838,7 +839,8 @@ subscriber.setCodeAndData(1, "publish_data_changed").then(() => { isOrderedCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is an ordered one. This API uses a callback to return the result. +Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. + **System capability**: SystemCapability.Notification.CommonEvent @@ -851,7 +853,7 @@ Checks whether this common event is an ordered one. This API uses a callback to **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is an ordered one. function isOrderedCallback(err, isOrdered) { @@ -870,6 +872,7 @@ isOrderedCommonEvent(): Promise\ Checks whether this common event is an ordered one. This API uses a promise to return the result. + **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -881,7 +884,7 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); @@ -894,7 +897,8 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { isStickyCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is a sticky one. This API uses a callback to return the result. +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. + **System capability**: SystemCapability.Notification.CommonEvent @@ -907,7 +911,7 @@ Checks whether this common event is a sticky one. This API uses a callback to re **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is a sticky one. function isStickyCallback(err, isSticky) { @@ -926,6 +930,7 @@ isStickyCommonEvent(): Promise\ Checks whether this common event is a sticky one. This API uses a promise to return the result. + **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -937,7 +942,7 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); @@ -950,7 +955,7 @@ subscriber.isStickyCommonEvent().then((isSticky) => { abortCommonEvent(callback: AsyncCallback\): void -Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a callback to return the result. +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -963,7 +968,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for common event aborting. function abortCallback(err) { @@ -993,7 +998,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); @@ -1006,7 +1011,7 @@ subscriber.abortCommonEvent().then(() => { clearAbortCommonEvent(callback: AsyncCallback\): void -Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a callback to return the result. +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1019,7 +1024,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for clearing the aborted state of the current common event. function clearAbortCallback(err) { @@ -1049,7 +1054,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); @@ -1062,7 +1067,7 @@ subscriber.clearAbortCommonEvent().then(() => { getAbortCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a callback to return the result. +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1075,7 +1080,7 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is in the aborted state. function getAbortCallback(err, AbortCommonEvent) { @@ -1105,7 +1110,7 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); @@ -1118,7 +1123,7 @@ subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { getSubscribeInfo(callback: AsyncCallback\): void -Obtains the subscriber information. This API uses a callback to return the result. +Obtains the subscriber information. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1131,7 +1136,7 @@ Obtains the subscriber information. This API uses a callback to return the resul **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for subscriber information obtaining. function getSubscribeInfoCallback(err, SubscribeInfo) { @@ -1161,7 +1166,7 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getSubscribeInfo().then((SubscribeInfo) => { console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); @@ -1174,7 +1179,7 @@ subscriber.getSubscribeInfo().then((SubscribeInfo) => { finishCommonEvent(callback: AsyncCallback\): void -Finishes this ordered common event. This API uses a callback to return the result. +Finishes this ordered common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1187,7 +1192,7 @@ Finishes this ordered common event. This API uses a callback to return the resul **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. function finishCommonEventCallback(err) { @@ -1217,7 +1222,7 @@ Finishes this ordered common event. This API uses a promise to return the result **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index ee5cf3137c7aa5d1ef6cb8ef1c1ef47ef8b35236..a166781108683f6b6fb53673da4deacd99882b26 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -22,6 +22,7 @@ Adds a contact. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------ | | contact | [Contact](#contact) | Yes | Contact information. | @@ -31,7 +32,7 @@ Adds a contact. This API uses an asynchronous callback to return the result. ```js contact.addContact({ - fullName: {fullName: 'xxx'}, + name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] }, (err, data) => { if (err) { @@ -54,11 +55,13 @@ Adds a contact. This API uses a promise to return the result. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------ | | contact | [Contact](#contact) | Yes | Contact information.| **Return Value** + | Type | Description | | --------------------- | ------------------------------------------- | | Promise<number> | Promise used to return the contact ID.| @@ -89,6 +92,7 @@ Deletes a contact based on the specified contact key. This API uses an asynchron **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------ | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -118,11 +122,13 @@ Deletes a contact based on the specified contact key. This API uses a promise to **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| **Return Value** + | Type | Description | | ------------------- | --------------------------------------------- | | Promise<void> | Promise used to return the result.| @@ -150,6 +156,7 @@ Updates a contact based on the specified contact information. This API uses an a **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------ | | contact | [Contact](#contact) | Yes | Contact information. | @@ -182,6 +189,7 @@ Updates a contact based on the specified contact information and attributes. Thi **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------ | | contact | [Contact](#contact) | Yes | Contact information. | @@ -192,10 +200,10 @@ Updates a contact based on the specified contact information and attributes. Thi ```js contact.updateContact({ - fullName: {fullName: 'xxx'}, + name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] - },{ - attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] + }, { + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err) => { if (err) { console.log('updateContact callback: err->${JSON.stringify(err)}'); @@ -217,12 +225,14 @@ Updates a contact based on the specified contact information and attributes. Thi **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ------- | --------------------------------------- | ---- | ------------------ | | contact | [Contact](#contact) | Yes | Contact information. | | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes.| **Return Value** + | Type | Description | | ------------------- | ------------------------------------------------- | | Promise<void> | Promise used to return the result.| @@ -231,7 +241,7 @@ Updates a contact based on the specified contact information and attributes. Thi ```js let promise = contact.updateContact({ - fullName: {fullName: 'xxx'}, + name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] }, { attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] @@ -255,6 +265,7 @@ Checks whether the ID of this contact is in the local address book. This API use **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | id | number | Yes | Contact ID. Each contact corresponds to one ID. | @@ -284,11 +295,13 @@ Checks whether the ID of this contact is in the local address book. This API use **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------ | | id | number | Yes | Contact ID. Each contact corresponds to one ID.| **Return Value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. The value **true** indicates that the contact ID is in the local address book, and the value **false** indicates the opposite.| @@ -316,6 +329,7 @@ Checks whether a contact is included in my card. This API uses an asynchronous c **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | id | number | Yes | Contact ID. | @@ -345,11 +359,13 @@ Checks whether a contact is included in my card. This API uses a promise to retu **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | id | number | Yes | Contact ID.| **Return Value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. The value **true** indicates that the contact is included in my card, and the value **false** indicates the opposite.| @@ -377,6 +393,7 @@ Queries my card. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | | callback | AsyncCallback<[Contact](#contact)> | Yes | Callback used to return the result.| @@ -405,6 +422,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | | attrs | [ContactAttributes](#contactattributes) | Yes | List of contact attributes. | @@ -414,7 +432,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn ```js contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryMyCard callback: err->${JSON.stringify(err)}`); @@ -436,11 +454,13 @@ Queries my card based on the specified contact attributes. This API uses a promi **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ------------------ | | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes.| **Return Value** + | Type | Description | | ---------------------------------- | ------------------------------------------- | | Promise<[Contact](#contact)> | Promise used to return the result.| @@ -449,7 +469,7 @@ Queries my card based on the specified contact attributes. This API uses a promi ```js let promise = contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryMyCard success: data->${JSON.stringify(data)}`); @@ -467,9 +487,10 @@ Selects a contact. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.Contacts and SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback<Array<[Contact](#contact)>> | Yes | Callback used to return the result.| @@ -495,9 +516,10 @@ Selects a contact. This API uses a promise to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.Contacts and SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Return Value** + | Type | Description | | ----------------------------------------------- | ------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -525,6 +547,7 @@ Queries a contact based on the specified key. This API uses an asynchronous call **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -554,6 +577,7 @@ Queries contacts based on the specified key and application. This API uses an as **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -588,6 +612,7 @@ Queries contacts based on the specified key and attributes. This API uses an asy **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -620,6 +645,7 @@ Queries contacts based on the specified key, application, and attributes. This A **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -658,6 +684,7 @@ Queries contacts based on the specified key, application, and attributes. This A **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | -------------------------------------- | | key | string | Yes | Contact key. Each contact corresponds to one key.| @@ -665,6 +692,7 @@ Queries contacts based on the specified key, application, and attributes. This A | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ---------------------------------- | ----------------------------------------------- | | Promise<[Contact](#contact)> | Promise used to return the result.| @@ -699,6 +727,7 @@ Queries all contacts. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | callback | AsyncCallback<Array<[Contact](#contact)>> | Yes | Callback used to return the result.| @@ -727,6 +756,7 @@ Queries all contacts based on the specified application. This API uses an asynch **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | holder | [Holder](#holder) | Yes | Application that creates the contacts. | @@ -760,6 +790,7 @@ Queries all contacts based on the specified attributes. This API uses an asynchr **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | attrs | [ContactAttributes](#contactattributes) | Yes | List of contact attributes. | @@ -791,6 +822,7 @@ Queries all contacts based on the specified application and attributes. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | holder | [Holder](#holder) | Yes | Application that creates the contacts. | @@ -827,12 +859,14 @@ Queries all contacts based on the specified application and attributes. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ---------------------- | | holder | [Holder](#holder) | No | Application that creates the contacts.| | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ----------------------------------------------- | --------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -866,6 +900,7 @@ Queries contacts based on the specified phone number. This API uses an asynchron **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -895,6 +930,7 @@ Queries contacts based on the specified phone number and application. This API u **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -929,6 +965,7 @@ Queries contacts based on the specified phone number and attributes. This API us **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -961,6 +998,7 @@ Queries contacts based on the specified phone number, application, and attribute **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | ----------------------------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -998,6 +1036,7 @@ Queries contacts based on the specified phone number, application, and attribute **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | ----------- | --------------------------------------- | ---- | ---------------------- | | phoneNumber | string | Yes | Phone number of the contacts. | @@ -1005,6 +1044,7 @@ Queries contacts based on the specified phone number, application, and attribute | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ----------------------------------------------- | --------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -1038,6 +1078,7 @@ Queries contacts based on the specified email address. This API uses an asynchro **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | email | string | Yes | Email address of the contact. | @@ -1067,6 +1108,7 @@ Queries contacts based on the specified email address and application. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | -------------------------------------- | | email | string | Yes | Email address of the contact. | @@ -1101,6 +1143,7 @@ Queries contacts based on the specified email address and attributes. This API u **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ------------------------------------ | | email | string | Yes | Email address of the contact. | @@ -1133,6 +1176,7 @@ Queries contacts based on the specified email address, application, and attribut **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ------------------------------------ | | email | string | Yes | Email address of the contact. | @@ -1170,6 +1214,7 @@ Queries contacts based on the specified email address, application, and attribut **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ---------------------- | | email | string | Yes | Email address of the contact. | @@ -1177,6 +1222,7 @@ Queries contacts based on the specified email address, application, and attribut | attrs | [ContactAttributes](#contactattributes) | No | List of contact attributes. | **Return Value** + | Type | Description | | ----------------------------------------------- | --------------------------------------------------- | | Promise<Array<[Contact](#contact)>> | Promise used to return the result.| @@ -1210,6 +1256,7 @@ Queries all groups of this contact. This API uses an asynchronous callback to re **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback<Array<[Group](#group)>> | Yes | Callback used to return the result.| @@ -1238,6 +1285,7 @@ Queries all groups of this contact based on the specified application. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | | holder | Holder | Yes | Application that creates the contacts. | @@ -1271,11 +1319,13 @@ Queries all groups of this contact based on the specified application. This API **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------- | ---- | ---------------------- | | holder | [Holder](#holder) | No | Application that creates the contacts.| **Return Value** + | Type | Description | | ------------------------------------------- | ------------------------------------------------- | | Promise<Array<[Group](#group)>> | Promise used to return the result.| @@ -1307,6 +1357,7 @@ Queries all applications that have created contacts. This API uses an asynchrono **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<Array<[Holder](#holder)>> | Yes | Callback used to return the result.| @@ -1335,6 +1386,7 @@ Queries all applications that have created contacts. This API uses a promise to **System capability**: SystemCapability.Applications.ContactsData **Return Value** + | Type | Description | | --------------------------------------------- | ------------------------------------------------------------ | | Promise<Array<[Holder](#holder)>> | Promise used to return the result.| @@ -1362,6 +1414,7 @@ Queries the key of a contact based on the specified contact ID. This API uses an **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | --------------------------------------- | | id | number | Yes | Contact ID. | @@ -1391,6 +1444,7 @@ Queries the key of a contact based on the specified contact ID and application. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | --------------------------------------- | | id | number | Yes | Contact ID. | @@ -1400,7 +1454,7 @@ Queries the key of a contact based on the specified contact ID and application. **Example** ```js - contact.queryKey(id, { + contact.queryKey(/*id*/1, { holderId: 0, bundleName: "", displayName: "" @@ -1425,12 +1479,14 @@ Queries the key of a contact based on the specified contact ID and application. **System capability**: SystemCapability.Applications.ContactsData **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------- | ---- | ---------------------- | | id | number | Yes | Contact ID. | | holder | [Holder](#holder) | No | Application that creates the contacts.| **Return Value** + | Type | Description | | --------------------- | ---------------------------------------------------- | | Promise<string> | Promise used to return the result.| @@ -1438,7 +1494,7 @@ Queries the key of a contact based on the specified contact ID and application. **Example** ```js - let promise = contact.queryKey(id, { + let promise = contact.queryKey(/*id*/1, { holderId: 0, bundleName: "", displayName: "" @@ -1553,7 +1609,7 @@ Or, create data by configuring a **ContactAttributes** object. ```js let contactAttributes = new contact.ContactAttributes(); -contactAttributes.attributes = ["ATTR_EMAIL"]; +contactAttributes.attributes = [contact.Attribute.ATTR_EMAIL]; ``` @@ -2191,4 +2247,4 @@ let website = { ```js let website = new contact.Website(); website.website = "website"; -``` +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index f6702d14d391a025bf9a16f2d8bf79a97772ed0a..5fedece20aac3dc30e68020964be1fbca1cefdfa 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -195,7 +195,7 @@ Moves to the specified row in the result set. **Example** ```ts -let goToRowNum = 2 +let goToRowNum = 2; let isGoToRow = resultSet.goToRow(goToRowNum); console.info('resultSet.goToRow: ' + isGoToRow); ``` @@ -223,7 +223,7 @@ Obtains the value in the form of a byte array based on the specified column and **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getBlob = resultSet.getBlob(columnIndex); console.info('resultSet.getBlob: ' + getBlob); @@ -231,7 +231,7 @@ console.info('resultSet.getBlob: ' + getBlob); ### getString -getString(columnIndex: number): *string* +getString(columnIndex: number): string Obtains the value in the form of a string based on the specified column and the current row. @@ -252,7 +252,7 @@ Obtains the value in the form of a string based on the specified column and the **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getString = resultSet.getString(columnIndex); console.info('resultSet.getString: ' + getString); @@ -281,7 +281,7 @@ Obtains the value in the form of a long integer based on the specified column an **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getLong = resultSet.getLong(columnIndex); console.info('resultSet.getLong: ' + getLong); @@ -310,7 +310,7 @@ Obtains the value in the form of a double-precision floating-point number based **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getDouble = resultSet.getDouble(columnIndex); console.info('resultSet.getDouble: ' + getDouble); @@ -353,14 +353,14 @@ Obtains the column index based on the column name. **Example** ```ts -let ColumnName = "name" -let getColumnIndex = resultSet.getColumnIndex(ColumnName) +let ColumnName = "name"; +let getColumnIndex = resultSet.getColumnIndex(ColumnName); console.info('resultSet.getColumnIndex: ' + getColumnIndex); ``` ### getColumnName -getColumnName(columnIndex: number): *string* +getColumnName(columnIndex: number): string Obtains the column name based on the column index. @@ -381,8 +381,8 @@ Obtains the column name based on the column index. **Example** ```ts -let columnIndex = 1 -let getColumnName = resultSet.getColumnName(columnIndex) +let columnIndex = 1; +let getColumnName = resultSet.getColumnName(columnIndex); console.info('resultSet.getColumnName: ' + getColumnName); ``` 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 5d393653ce602b60438df2b6f9e54f6ba9cb9fe6..779d30c40263eecd1a8ecf70209a95008aa228dd 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -726,7 +726,7 @@ Sets a **DataAbilityPredicates** object to specify the index column. 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. +Sets a **DataAbilityPredicates** object to match the field with data type Array\ and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -754,7 +754,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< 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. +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 diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 2f54d7d7c47b10403fbc96edf92ce1d55cdcb41b..4d2df994d96b7b0986782774e9d531a12750cac7 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -2,6 +2,8 @@ You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. +The APIs provided by **DataSharePredicates** correspond to the filter criteria of the database. Before using the APIs, you need to have basic database knowledge. + > **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. @@ -22,7 +24,7 @@ Provides methods for setting different **DataSharePredicates** objects. equalTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is equal to the specified value. Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. @@ -52,7 +54,7 @@ predicates.equalTo("NAME", "Rose") notEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is not equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is not equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -188,7 +190,7 @@ predicates.equalTo("NAME", "lisi") contains(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that contains the specified value. +Sets a **DataSharePredicates** object to search for the data that contains the specified value. Currently, only the RDB supports this **DataSharePredicates** object. @@ -218,7 +220,7 @@ predicates.contains("NAME", "os") beginsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that begins with the specified value. +Sets a **DataSharePredicates** object to search for the data that begins with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. @@ -248,7 +250,7 @@ predicates.beginsWith("NAME", "os") endsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that ends with the specified value. +Sets a **DataSharePredicates** object to search for the data that ends with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. @@ -278,7 +280,7 @@ predicates.endsWith("NAME", "os") isNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data whose value is null. +Sets a **DataSharePredicates** object to search for the data whose value is null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -307,7 +309,7 @@ predicates.isNull("NAME") isNotNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data whose value is not null. +Sets a **DataSharePredicates** object to search for the data whose value is not null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -336,7 +338,7 @@ predicates.isNotNull("NAME") like(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is similar to the specified value. +Sets a **DataSharePredicates** object to search for the data that matches the specified wildcard expression. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -347,7 +349,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match.| +| value | string | Yes | Wildcard expression to match.
In the expression, '%' represents zero, one, or more digits or characters, and '_' represents a single digit or character. It is case insensitive.| **Return value** @@ -366,7 +368,7 @@ predicates.like("NAME", "%os%") unlike(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is not not similar to the specified value. +Sets a **DataSharePredicates** object to search for the data that does not match the specified wildcard expression. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -377,7 +379,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match.| +| value | string | Yes | Wildcard expression to match.
In the expression, '%' represents zero, one, or more digits or characters, and '_' represents a single digit or character. It is case insensitive.| **Return value** @@ -396,7 +398,7 @@ predicates.unlike("NAME", "%os%") glob(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the specified string. +Sets a **DataSharePredicates** object to search for the data that matches the specified wildcard expression. Currently, only the RDB supports this **DataSharePredicates** object. @@ -407,7 +409,7 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match.| +| value | string | Yes | Wildcard expression to match.
In the expression, '*' represents zero, one, or more digits or characters, and '?' represents a single digit or character. It is case sensitive.| **Return value** @@ -426,7 +428,7 @@ predicates.glob("NAME", "?h*g") between(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is within the specified range. +Sets a **DataSharePredicates** object to search for the data that is within the specified range, including the start and end values. Currently, only the RDB supports this **DataSharePredicates** object. @@ -457,7 +459,7 @@ predicates.between("AGE", 10, 50) notBetween(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is out of the specified range. +Sets a **DataSharePredicates** object to search for the data that is out of the specified range, excluding the start and end values. Currently, only the RDB supports this **DataSharePredicates** object. @@ -488,7 +490,7 @@ predicates.notBetween("AGE", 10, 50) greaterThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is greater than the specified value. +Sets a **DataSharePredicates** object to search for the data that is greater than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -518,7 +520,7 @@ predicates.greaterThan("AGE", 10) lessThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is less than the specified value. +Sets a **DataSharePredicates** object to search for the data that is less than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -548,7 +550,7 @@ predicates.lessThan("AGE", 50) greaterThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is greater than or equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is greater than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -578,7 +580,7 @@ predicates.greaterThanOrEqualTo("AGE", 10) lessThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is less than or equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is less than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -777,7 +779,7 @@ predicates.indexedBy("SALARY_INDEX") in(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is within the specified value. +Sets a **DataSharePredicates** object to search for the data that is within the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -807,7 +809,7 @@ predicates.in("AGE", [18, 20]) notIn(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is not in the specified value. +Sets a **DataSharePredicates** object to search for the data that is not in the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -837,7 +839,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) prefixKey(prefix: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data with the specified key prefix. +Sets a **DataSharePredicates** object to search for the data with the specified key prefix. Currently, only the KVDB supports this **DataSharePredicates** object. @@ -866,7 +868,7 @@ predicates.prefixKey("NAME") inKeys(keys: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to match the data whose keys are within the given range. +Sets a **DataSharePredicates** object to search for the data whose keys are within the given range. Currently, only the KVDB supports this **DataSharePredicates** object. diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 6803d4edf50fc219bc37c4be79fc71687dd91457..153397a41d715c1814a143a4ff051e6964ba29eb 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -38,15 +38,21 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | -| name | string | Yes | Name of the **Preferences** instance. | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| name | string | Yes | Name of the **Preferences** instance.| | callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| **Example** +FA model: + ```js -var preferences = null; -data_preferences.getPreferences(this.context, 'mystore', function (err, object) { +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let preferences = null; +data_preferences.getPreferences(context, 'mystore', function (err, object) { if (err) { console.info("Failed to get the preferences. Cause: " + err); return; @@ -56,6 +62,28 @@ data_preferences.getPreferences(this.context, 'mystore', function (err, object) }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let preferences = null; +data_preferences.getPreferences(context, 'mystore', function (err, object) { + if (err) { + console.info("Failed to get the preferences. Cause: " + err); + return; + } + preferences = object; + console.info("Got the preferences successfully."); +}) +``` ## data_preferences.getPreferences @@ -66,21 +94,29 @@ Obtains a **Preferences** instance. This API uses a promise to return the result **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| **Return value** + | Type | Description | | ------------------------------------------ | ---------------------------------- | | Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| **Example** +FA model: + ```js -var preferences = null; -let promise = data_preferences.getPreferences(this.context, 'mystore') +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let preferences = null; +let promise = data_preferences.getPreferences(context, 'mystore'); promise.then((object) => { preferences = object; console.info("Got the preferences successfully."); @@ -89,6 +125,27 @@ promise.then((object) => { }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let preferences = null; +let promise = data_preferences.getPreferences(context, 'mystore'); +promise.then((object) => { + preferences = object; + console.info("Got the preferences successfully."); +}).catch((err) => { + console.info("Failed to get the preferences. Cause: " + err); +}) +``` ## data_preferences.deletePreferences @@ -103,23 +160,51 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + +FA model: + ```js -data_preferences.deletePreferences(this.context, 'mystore', function (err) { +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +data_preferences.deletePreferences(context, 'mystore', function (err) { if (err) { console.info("Failed to delete the preferences. Cause: " + err); - return + return; } console.info("Deleted the preferences successfully." ); }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +data_preferences.deletePreferences(context, 'mystore', function (err) { + if (err) { + console.info("Failed to delete the preferences. Cause: " + err); + return; + } + console.info("Deleted the preferences successfully." ); +}) +``` ## data_preferences.deletePreferences @@ -134,19 +219,28 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + +FA model: + ```js -let promise = data_preferences.deletePreferences(this.context, 'mystore') +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let promise = data_preferences.deletePreferences(context, 'mystore'); promise.then(() => { console.info("Deleted the preferences successfully."); }).catch((err) => { @@ -154,6 +248,25 @@ promise.then(() => { }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let promise = data_preferences.deletePreferences(context, 'mystore'); +promise.then(() => { + console.info("Deleted the preferences successfully."); +}).catch((err) => { + console.info("Failed to delete the preferences. Cause: " + err); +}) +``` ## data_preferences.removePreferencesFromCache @@ -166,15 +279,23 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + +FA model: + ```js -data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { if (err) { console.info("Failed to remove the preferences. Cause: " + err); return; @@ -183,6 +304,26 @@ data_preferences.removePreferencesFromCache(this.context, 'mystore', function (e }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { + if (err) { + console.info("Failed to remove the preferences. Cause: " + err); + return; + } + console.info("Removed the preferences successfully."); +}) +``` ## data_preferences.removePreferencesFromCache @@ -195,19 +336,28 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + +FA model: + ```js -let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore') +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); promise.then(() => { console.info("Removed the preferences successfully."); }).catch((err) => { @@ -215,6 +365,25 @@ promise.then(() => { }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); +promise.then(() => { + console.info("Removed the preferences successfully."); +}).catch((err) => { + console.info("Failed to remove the preferences. Cause: " + err); +}) +``` ## Preferences @@ -232,6 +401,7 @@ Obtains the value of a key. This API uses an asynchronous callback to return the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -260,6 +430,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -272,6 +443,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the | Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| **Example** + ```js let promise = preferences.get('startup', 'default'); promise.then((data) => { @@ -290,6 +462,7 @@ Obtains an **Object** instance that contains all KV pairs. This API uses an asyn **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | callback | AsyncCallback<Object> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** is the **Object** instance obtained. Otherwise, **err** is an error code.| @@ -318,11 +491,13 @@ Obtains an **Object** instance that contains all KV pairs. This API uses a promi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | --------------------- | ------------------------------------------- | | Promise<Object> | Promise used to return the **Object** instance obtained.| **Example** + ```js let promise = preferences.getAll(); promise.then((value) => { @@ -343,6 +518,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | @@ -350,6 +526,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. | **Example** + ```js preferences.put('startup', 'auto', function (err) { if (err) { @@ -370,17 +547,20 @@ Writes data to this **Preferences** instance. This API uses a promise to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | | value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.put('startup', 'auto'); promise.then(() => { @@ -395,17 +575,19 @@ promise.then(() => { has(key: string, callback: AsyncCallback<boolean>): void -Checks whether this **Preferences** instance contains a KV pair of the given key. This API uses an asynchronous callback to return the result.. +Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to check. It cannot be empty. | | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** + ```js preferences.has('startup', function (err, isExist) { if (err) { @@ -425,16 +607,18 @@ preferences.has('startup', function (err, isExist) { has(key: string): Promise<boolean> -Checks whether this **Preferences** instance contains data with the given key. This API uses a promise to return the result. +Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the data to check. It cannot be empty.| **Return value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| @@ -464,12 +648,14 @@ Deletes a KV pair from this **Preferences** instance. This API uses an asynchron **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.delete('startup', function (err) { if (err) { @@ -490,16 +676,19 @@ Deletes a KV pair from this **Preferences** instance. This API uses a promise to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.delete('startup'); promise.then(() => { @@ -514,16 +703,18 @@ promise.then(() => { flush(callback: AsyncCallback<void>): void -Saves the data of the **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. +Saves the data of this **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.flush(function (err) { if (err) { @@ -539,16 +730,18 @@ preferences.flush(function (err) { flush(): Promise<void> -Saves the data of the **Preferences** instance to a file asynchronously. This API uses a promise to return the result. +Saves the data of this **Preferences** instance to a file asynchronously. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.flush(); promise.then(() => { @@ -568,11 +761,13 @@ Clears this **Preferences** instance. This API uses an asynchronous callback to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.clear(function (err) { if (err) { @@ -593,11 +788,13 @@ Clears this **Preferences** instance. This API uses a promise to return the resu **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.clear() promise.then(() => { @@ -617,23 +814,25 @@ Subscribes to data changes. A callback will be triggered to return the new value **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Event type to subscribe to. The value **change** indicates data change events.| | callback | Callback<{ key : string }> | Yes | Callback invoked to return data changes. | **Example** + ```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { console.info("Failed to get the preferences."); return; } - var observer = function (key) { + let observer = function (key) { console.info("The key " + key + " changed."); } preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { + preferences.put('startup', 'manual', function (err) { if (err) { console.info("Failed to put the value of 'startup'. Cause: " + err); return; @@ -661,19 +860,21 @@ Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------- | ---- | ------------------------------------------ | | type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | | callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| **Example** + ```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to get preferences."); + console.info("Failed to get the preferences."); return; } - var observer = function (key) { + let observer = function (key) { console.info("The key " + key + " changed."); } preferences.on('change', observer); 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 3098499d48ca52b0251cfb9648cc032fc26e2652..28cde770498760d5eac09dc79c5b495f91d05c4a 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -6,26 +6,25 @@ A result set is a set of results returned after the relational database (RDB) qu > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Usage You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain a **resultSet** object. ```js import dataRdb from '@ohos.data.rdb'; -let predicates = new dataRdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("AGE", 18) -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +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(TAG + "resultSet columnNames:" + resultSet.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSet.columnCount);}) + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); +}); ``` ## ResultSet Provides methods to access the result set, which is obtained by querying the RDB store. - ### Attributes **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -42,7 +41,6 @@ Provides methods to access the result set, which is obtained by querying the RDB | isStarted | boolean | Yes| Whether the cursor has been moved.| | isClosed | boolean | Yes| Whether the result set is closed.| - ### getColumnIndex getColumnIndex(columnName: string): number @@ -52,25 +50,27 @@ 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** + ```js - 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")) + 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 @@ -80,23 +80,25 @@ 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** + ```js - const id = resultSet.getColumnName(0) - const name = resultSet.getColumnName(1) - const age = resultSet.getColumnName(2) + const id = resultSet.getColumnName(0); + const name = resultSet.getColumnName(1); + const age = resultSet.getColumnName(2); ``` - ### goTo goTo(offset:number): boolean @@ -106,28 +108,30 @@ Moves the cursor to the row based on the specified offset. **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** + ```js - let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoto.then((resultSet) { - resultSet.goTo(1) - resultSet.close() + resultSet.goTo(1); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToRow goToRow(position: number): boolean @@ -137,28 +141,30 @@ Moves the cursor to the specified row in the result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **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.| **Example** + ```js - let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygotorow.then((resultSet) { - resultSet.goToRow(5) - resultSet.close() + resultSet.goToRow(5); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToFirstRow goToFirstRow(): boolean @@ -169,23 +175,24 @@ Moves the cursor to the first 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** + ```js - let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoFirst.then((resultSet) { - resultSet.goToFirstRow() - resultSet.close() + resultSet.goToFirstRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToLastRow goToLastRow(): boolean @@ -195,23 +202,24 @@ 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** + ```js - let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoLast.then((resultSet) { - resultSet.goToLastRow() - resultSet.close() + resultSet.goToLastRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToNextRow goToNextRow(): boolean @@ -221,23 +229,24 @@ Moves the cursor to the next row in 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** + ```js - let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoNext.then((resultSet) { - resultSet.goToNextRow() - resultSet.close() + resultSet.goToNextRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToPreviousRow goToPreviousRow(): boolean @@ -247,23 +256,24 @@ Moves the cursor to the previous row in 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** + ```js - let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoPrev.then((resultSet) { - resultSet.goToPreviousRow() - resultSet.close() + resultSet.goToPreviousRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### getBlob getBlob(columnIndex: number): Uint8Array @@ -273,21 +283,23 @@ Obtains the value in the specified column in the current row as a byte array. **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** + ```js - const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) + const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` - ### getString getString(columnIndex: number): string @@ -297,21 +309,23 @@ Obtains the value in the specified column in the current row as a 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| | -------- | -------- | | string | Value in the specified column as a string.| **Example** + ```js - const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` - ### getLong getLong(columnIndex: number): number @@ -321,21 +335,23 @@ 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** + ```js - const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` - ### getDouble getDouble(columnIndex: number): number @@ -345,21 +361,23 @@ 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** + ```js - const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` - ### isColumnNull isColumnNull(columnIndex: number): boolean @@ -369,21 +387,23 @@ 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** + ```js - const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) + const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` - ### close close(): void @@ -393,12 +413,13 @@ Closes this result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** + ```js - let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE") - let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); + let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promiseClose.then((resultSet) { - resultSet.close() + resultSet.close(); }).catch((err) => { - console.log('Failed to close resultset') - }) + console.log('Failed to close resultset'); + }); ``` diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md index a1e16d5e0b970a82d9b4e866eb053cb014ced89f..46a110814dc474f66393135a91313ab5df03b98e 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -1,5 +1,7 @@ # Device Information +The **deviceInfo** module provides product information. + > **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. 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 9d51475957c8e9c891980c0d42880a6b1db649de..46c9d2e80e30fad1c21827d41de7418934f3bbdc 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -10,6 +10,7 @@ System applications can call the APIs to do the following: - Query the trusted device list. - Query local device information, including the device name, type, and ID. - Publish device information for discovery purposes. + > **NOTE** > > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,7 +19,7 @@ System applications can call the APIs to do the following: ## Modules to Import -``` +```js import deviceManager from '@ohos.distributedHardware.deviceManager'; ``` @@ -32,23 +33,37 @@ Creates a **DeviceManager** instance. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------------- | ---- | ------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| + + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------------------------------------ | + | bundleName | string | Yes | Bundle name of an application. | + | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600102 | Failed to obtain the service. | **Example** -``` -deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { - if (err) { - console.info("createDeviceManager err:" + JSON.stringify(err)); + ```js + try { + deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { + if (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); return; - } - console.info("createDeviceManager success"); - let dmInstance = data; -}); -``` + } + console.info("createDeviceManager success"); + let dmInstance = data; + }); + } catch(err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ## DeviceInfo @@ -191,7 +206,7 @@ Defines published device information. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ------------- | --------------------------------- | ---- | ----------------- | | publishId | number | Yes | ID used to identify a publication period.| | mode | [DiscoverMode ](#discovermode) | Yes | Device discovery mode. | @@ -202,7 +217,6 @@ Defines published device information. 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**. - ### release release(): void @@ -211,12 +225,23 @@ Releases this **DeviceManager** instance when it is no longer used. **System capability**: SystemCapability.DistributedHardware.DeviceManager -**Example** +**Error codes** -```js -dmInstance.release(); -``` +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**Example** + ```js + try { + dmInstance.release(); + } catch (err) { + console.error("release errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### getTrustedDeviceListSync @@ -228,16 +253,27 @@ Obtains all trusted devices synchronously. **Return value** -| Name | Description | -| -------------------------------------- | --------- | -| Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| + | Name | Description | + | -------------------------------------- | --------- | + | Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| -**Example** +**Error codes** -```js -var deviceInfoList = dmInstance.getTrustedDeviceListSync(); -``` +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**Example** + + ```js + try { + var deviceInfoList = dmInstance.getTrustedDeviceListSync(); + } catch (err) { + console.error("getTrustedDeviceListSync errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### getTrustedDeviceList8+ @@ -248,17 +284,33 @@ Obtains all trusted devices. This API uses an asynchronous callback to return th **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------- | -| callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | Yes | Callback used to return the list of trusted devices.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------- | + | callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | Yes | Callback used to return the list of trusted devices.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.getTrustedDeviceList((err, data) => { - console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + try { + dmInstance.getTrustedDeviceList((err, data) => { + if (err) { + console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); + return; + } console.log('get trusted device info: ' + JSON.stringify(data)); - } - ); + }); + } catch (err) { + console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### getTrustedDeviceList8+ @@ -270,16 +322,26 @@ Obtains all trusted devices. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the list of trusted devices.| + + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the list of trusted devices.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.getTrustedDeviceList().then((data) => { - console.log('get trusted device info: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + dmInstance.getTrustedDeviceList().then((data) => { + console.log('get trusted device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); }); ``` @@ -292,16 +354,29 @@ Obtains local device information synchronously. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** -| Name | Description | -| -------------------------------------- | --------- | -| Array<[DeviceInfo](#deviceinfo)> | List of local devices obtained.| + + | Name | Description | + | ------------------------- | ---------------- | + | [DeviceInfo](#deviceinfo) | List of local devices obtained.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - var deviceInfo = dmInstance.getLocalDeviceInfoSync(); + try { + var deviceInfo = dmInstance.getLocalDeviceInfoSync(); + } catch (err) { + console.error("getLocalDeviceInfoSync errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### getLocalDeviceInfo8+ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void @@ -311,17 +386,33 @@ Obtains local device information. This API uses an asynchronous callback to retu **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | Yes | Callback used to return the local device information.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------- | + | callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | Yes | Callback used to return the local device information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.getLocalDeviceInfo((err, data) => { - console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); - console.log('get local device info: ' + JSON.stringify(data)); + try { + dmInstance.getLocalDeviceInfo((err, data) => { + if (err) { + console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); + return; } - ); + console.log('get local device info: ' + JSON.stringify(data)); + }); + } catch (err) { + console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### getLocalDeviceInfo8+ @@ -333,16 +424,26 @@ Obtains local device information. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the local device information.| + + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the local device information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| ------- | --------------------------------------------------------------- | +| 11600101| Failed to execute the function. | **Example** + ```js - dmInstance.getLocalDeviceInfo().then((data) => { - console.log('get local device info: ' + JSON.stringify(data)); + dmInstance.getLocalDeviceInfo().then((data) => { + console.log('get local device info: ' + JSON.stringify(data)); }).catch((err) => { - console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); }); ``` @@ -355,11 +456,22 @@ Starts to discover peripheral devices. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------------------------- | ---- | ----- | -| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + + | Name | Type | Mandatory| Description | + | ------------- | ------------------------------- | ---- | ----- | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600104 | Discovery invalid. | **Example** + ```js // Automatically generate a unique subscription ID. var subscribeId = Math.floor(Math.random() * 10000 + 1000); @@ -372,7 +484,11 @@ Starts to discover peripheral devices. "isWakeRemote": false, "capability": 1 }; - dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. + try { + dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. + } catch (err) { + console.error("startDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### startDeviceDiscovery9+
@@ -384,10 +500,20 @@ Starts to discover peripheral devices and filters discovered devices. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------------------------- | ---- | ----- | -| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| -| filterOptions | string | No | Options for filtering discovered devices.| + + | Name | Type | Mandatory | Description | + | ------------- | ------------------------------- | ---- | ----- | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + | filterOptions | string | No | Options for filtering discovered devices.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600104 | Discovery invalid. | **Example** @@ -412,7 +538,11 @@ Starts to discover peripheral devices and filters discovered devices. } ] }; - dmInstance.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions)); // The deviceFound callback is invoked to notify the application when a device is discovered. + try { + dmInstance.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions)); // The deviceFound callback is invoked to notify the application when a device is discovered. + } catch (err) { + console.error("startDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### stopDeviceDiscovery @@ -424,14 +554,28 @@ Stops device discovery. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ----- | -| subscribeId | number | Yes | Subscription ID.| + + | Name | Type | Mandatory | Description | + | ----------- | ------ | ---- | ----- | + | subscribeId | number | Yes | Subscription ID.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery. - dmInstance.stopDeviceDiscovery(subscribeId); + try { + dmInstance.stopDeviceDiscovery(subscribeId); + } catch (err) { + console.error("stopDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### publishDeviceDiscovery9+
@@ -443,11 +587,22 @@ Publishes device information for discovery purposes. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----- | -| publishInfo | [PublishInfo](#publishinfo) | Yes | Device information to publish.| + + | Name | Type | Mandatory| Description | + | ------------- | ------------------------------- | ---- | ----- | + | publishInfo | [PublishInfo](#publishinfo) | Yes | Device information to publish.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600105 | Publish invalid. | **Example** + ```js // Automatically generate a unique subscription ID. var publishId = Math.floor(Math.random() * 10000 + 1000); @@ -457,9 +612,13 @@ Publishes device information for discovery purposes. "freq": 2, // High frequency "ranging": 1 // The device supports reporting the distance to the discovery initiator. }; - dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published. + try { + dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published. + } catch (err) { + console.error("publishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` - + ### unPublishDeviceDiscovery9+
unPublishDeviceDiscovery(publishId: number): void @@ -470,14 +629,27 @@ Stops publishing device information. **Parameters** -| Name | Type| Mandatory| Description | -| ----------- | -------- | ---- | ----- | -| publishId | number | Yes | Publish ID.| + | Name | Type| Mandatory| Description | + | ----------- | -------- | ---- | ----- | + | publishId | number | Yes | Publish ID.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js // The publishId input must be the same as that automatically generated in publishDeviceDiscovery. - dmInstance.unPublishDeviceDiscovery(publishId); + try { + dmInstance.unPublishDeviceDiscovery(publishId); + } catch (err) { + console.error("unPublishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### authenticateDevice @@ -489,13 +661,24 @@ Authenticates a device. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------------- | ---- | ------- | -| deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | -| authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | -| callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| + + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | + | authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | + | callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600103 | Authentication invalid. | **Example** + ```js // Information about the device to authenticate. The information can be obtained from the device discovery result. var deviceInfo ={ @@ -507,14 +690,18 @@ Authenticates a device. "authType": 1, // Authentication type. The value 1 means no account PIN authentication. "extraInfo": {} } - dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { + try { + dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { if (err) { - console.info(TAG + "authenticateDevice err:" + JSON.stringify(err)); + console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message); return; } - console.info(TAG + "authenticateDevice result:" + JSON.stringify(data)); - token = data.pinToken; - }); + console.info("authenticateDevice result:" + JSON.stringify(data)); + let token = data.pinToken; + }); + } catch (err) { + console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### unAuthenticateDevice8+ @@ -527,16 +714,28 @@ Deauthenticates a device. **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | ---- | ----- | -| deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| + | Name | Type | Mandatory | Description | + | ---------- | ------------------------- | ---- | ----- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.unAuthenticateDevice(deviceInfo); + try { + dmInstance.unAuthenticateDevice(deviceInfo); + } catch (err) { + console.error("unAuthenticateDevice errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### verifyAuthInfo verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void @@ -546,27 +745,132 @@ Verifies authentication information. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------- | -| authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | -| authInfo | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------- | + | authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | + | callback | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js let authInfo = { "authType": 1, "token": xxxxxx, "extraInfo": {} } - dmInstance.verifyAuthInfo(authInfo, (err, data) => { + try { + dmInstance.verifyAuthInfo(authInfo, (err, data) => { if (err) { - console.info(TAG + "verifyAuthInfo err:" + JSON.stringify(err)); + console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message); return; } - console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data)); + console.info("verifyAuthInfo result:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +### setUserOperation9+
+ +setUserOperation(operateAction: number, params: string): void; + +Sets a user operation action. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------------- | --------------- | ---- | ------------------- | + | operateAction | number | Yes | User operation action. | + | params | string | Yes | Input parameters of the user.| + +**Example** + + ```js + try { + /* + operateAction = 0 - Grant the permission. + operateAction = 1 - Revoke the permission. + operateAction = 2 - The user operation in the permission request dialog box times out. + operateAction = 3 - Cancel the display of the PIN box. + operateAction = 4 - Cancel the display of the PIN text box. + operateAction = 5 - Confirm in the pin text box. + */ + let operation = 0; + this.dmInstance.setUserOperation(operation, "extra") + } catch (err) { + console.error("setUserOperation errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +### on('uiStateChange')9+
+ +on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; + +Subscribes to UI status changes. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------ | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'uiStateChange'** indicates a UI status change event.| + | callback | Callback<{ param: string}> | Yes | Callback used to return the UI status. | + +**Example** + + ```js + try { + dmInstance.on('uiStateChange', (data) => { + console.log("uiStateChange executed, dialog closed" + JSON.stringify(data)) + var tmpStr = JSON.parse(data.param) + this.isShow = tmpStr.verifyFailed + console.log("uiStateChange executed, dialog closed" + this.isShow) + if (!this.isShow) { + this.destruction() + } }); + } catch (err) { + console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); + } ``` +### off('uiStateChange')9+
+ +off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; + +Unsubscribes from UI status changes. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'uiStateChange'** indicates a UI status change event.| + | callback | Callback<{ param: string}> | Yes | Callback used to return the UI status.| + +**Example** + + ```js + try { + dmInstance.off('uiStateChange'); + } catch (err) { + console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### on('deviceStateChange') @@ -577,20 +881,24 @@ Subscribes to changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| -| callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state. | + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used to return the device information and state. | **Example** + ```js - dmInstance.on('deviceStateChange', (data) => { - console.info("deviceStateChange on:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('deviceStateChange', (data) => { + console.info("deviceStateChange on:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("deviceStateChange errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### off('deviceStateChange') off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void @@ -600,20 +908,23 @@ 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 a device state change event. | -| callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. | + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo)  }> | Yes | Callback used to return the device information and state.| **Example** -```js -dmInstance.off('deviceStateChange', (data) => { + ```js + try { + dmInstance.off('deviceStateChange', (data) => { console.info('deviceStateChange' + JSON.stringify(data)); - } -); -``` - + }); + } catch (err) { + console.error("deviceStateChange errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### on('deviceFound') @@ -624,17 +935,22 @@ Subscribes to device discovery events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------- | -| type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| -| callback | Callback<{ subscribeId: number, device: DeviceInfo }> | Yes | Callback used for device discovery. | + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | -------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| + | callback | Callback<{ subscribeId: number, device: DeviceInfo }> | Yes | Callback used for device discovery. | **Example** + ```js - dmInstance.on('deviceFound', (data) => { - console.info("deviceFound:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('deviceFound', (data) => { + console.info("deviceFound:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("deviceFound errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### off('deviceFound') @@ -646,17 +962,22 @@ Unsubscribes from device discovery events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------- | -| type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | -| callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | + | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used to return the device information and state.| **Example** + ```js - dmInstance.off('deviceFound', (data) => { - console.info('deviceFound' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + }); + } catch (err) { + console.error("deviceFound errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('discoverFail') @@ -668,17 +989,22 @@ Subscribes to device discovery failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| -| callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | **Example** + ```js - dmInstance.on('discoverFail', (data) => { - this.log("discoverFail on:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('discoverFail', (data) => { + console.info("discoverFail on:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("discoverFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### off('discoverFail') @@ -690,17 +1016,22 @@ Unsubscribes from device discovery failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------- | -| type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | -| callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ----------------- | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure.| **Example** + ```js - dmInstance.off('deviceFound', (data) => { - console.info('deviceFound' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('discoverFail', (data) => { + console.info('discoverFail' + JSON.stringify(data)); + }); + } catch (err) { + console.error("discoverFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('publishSuccess')9+
@@ -712,18 +1043,24 @@ Subscribes to device information publication success events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | -------------------------- | -| type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published.| -| callback | Callback<{ publishId: number }> | Yes | Callback invoked to return the publish ID. | + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------------- | ---- | -------------------------- | + | type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published.| + | callback | Callback<{ publishId: number }> | Yes | Callback used to return the publish ID. | + **Example** -```js -dmInstance.on('publishSuccess', (data) => { + + ```js + try { + dmInstance.on('publishSuccess', (data) => { console.info("publishSuccess:" + JSON.stringify(data)); - } -); -``` + }); + } catch (err) { + console.error("publishSuccess errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### off('publishSuccess')9+
@@ -734,17 +1071,22 @@ Unsubscribes from device information publication success events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | --------------------------- | -| type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published. | -| callback | Callback<{ publishId: number }> | Yes | Callback used to return the publish ID.| + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published. | + | callback | Callback<{ publishId: number }> | Yes | Callback used to return the publish ID.| **Example** + ```js - dmInstance.off('publishSuccess', (data) => { - console.info('publishSuccess' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('publishSuccess', (data) => { + console.info('publishSuccess' + JSON.stringify(data)); + }); + } catch (err) { + console.error("publishSuccess errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('publishFail')9+
@@ -756,17 +1098,22 @@ Subscribes to device information publication failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails.| -| callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the publication failure. | + + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails.| + | callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the publication failure. | **Example** + ```js - dmInstance.on('publishFail', (data) => { - this.log("publishFail on:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('publishFail', (data) => { + console.info("publishFail on:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("publishFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### off('publishFail')9+
@@ -778,17 +1125,22 @@ Unsubscribes from device information publication failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ----------------- | -| type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails. | -| callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the device discovery failure.| + + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------------------------- | ---- | ----------------- | + | type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails. | + | callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the device discovery failure.| **Example** + ```js - dmInstance.off('publishFail', (data) => { - console.info('publishFail' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('publishFail', (data) => { + console.info('publishFail' + JSON.stringify(data)); + }); + } catch (err) { + console.error("publishFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('serviceDie') @@ -800,20 +1152,24 @@ 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. | + + | 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** + ```js - dmInstance.on("serviceDie", () => { - console.info("serviceDie on"); - } - ); + try { + dmInstance.on("serviceDie", () => { + console.info("serviceDie on"); + }); + } catch (err) { + console.error("serviceDie errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### off('serviceDie') off(type: 'serviceDie', callback?: () => void): void @@ -823,15 +1179,20 @@ 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. | + + | 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** + ```js - dmInstance.off("serviceDie", () => { - console.info("serviceDie off"); - } - ); + try { + dmInstance.off("serviceDie", () => { + console.info("serviceDie off"); + }); + } catch (err) { + console.error("serviceDie errCode:" + err.code + ",errMessage:" + err.message); + } ``` diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 81ee6f74b796de60b190f06b3f2a8a719f8569c3..382806418cb94f0e7be4a7c31a3feded938fee38 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -41,7 +41,7 @@ Checks whether the application specified by **bundleName** is in the idle state. | Name | Type | Mandatory | Description | | ---------- | ---------------------------- | ---- | ---------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the value of bundleName is valid, null will be returned.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns the idle state of the application if the specified **bundleName** is valid; returns **null** otherwise.| **Example** @@ -73,7 +73,7 @@ Checks whether the application specified by **bundleName** is in the idle state. | Type | Description | | ---------------------- | ---------------------------------------- | -| Promise<boolean> | Promise used to return the result. If the value of **bundleName** is valid, **null** will be returned.| +| Promise<boolean> | Promise used to return the result. Returns the idle state of the application if the specified **bundleName** is valid; returns **null** otherwise.| **Example** @@ -275,7 +275,7 @@ Queries the application usage duration statistics in the specified time frame at | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| Promise<Array<[BundleStateInfo](#bundlestateinfo)>> | Promise used to return the result.| +| Promise<Array<[BundleStateInfo](#bundlestateinfo)>> | Promise used to return the result. | **Example** @@ -309,7 +309,7 @@ Queries events of all applications based on the specified start time and end tim | -------- | ---------------------------------------- | ---- | --------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result. | **Example** @@ -350,7 +350,7 @@ Queries events of all applications based on the specified start time and end tim | Type | Description | | ---------------------------------------- | -------------------------------------- | -| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result. | **Example** @@ -380,7 +380,7 @@ Queries events of this application based on the specified start time and end tim | -------- | ---------------------------------------- | ---- | --------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result. | **Example** @@ -417,7 +417,7 @@ Queries events of this application based on the specified start time and end tim | Type | Description | | ---------------------------------------- | -------------------------------------- | -| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result. | **Example** @@ -455,7 +455,7 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses a | Type | Description | | ---------------------------------------- | ---------------------------------- | -| Promise<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Promise used to return the result. | **Example** @@ -486,7 +486,7 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses a getRecentlyUsedModules(callback: AsyncCallback<Array<BundleActiveModuleInfo>>): void -This API uses an asynchronous callback to return at most 1000 records sorted by time (most recent first). +Obtains FA usage records. This API uses an asynchronous callback to return a maximum of 1000 FA usage records sorted by time in descending order. **Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO @@ -498,7 +498,7 @@ This API uses an asynchronous callback to return at most 1000 records sorted by | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result. | **Example** @@ -532,8 +532,8 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| maxNum | number | Yes | Maximum number of returned records. The maximum and default value is **1000**.| -| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result.| +| maxNum | number | Yes | Maximum number of returned records. The maximum value is **1000**.| +| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result. | **Example** @@ -578,14 +578,14 @@ Queries the priority group of the application specified by **bundleName**. If ** **Example** ```javascript -// Promise with bundleName +// Promise mode when bundleName is specified let bundleName = "com.ohos.camera"; bundleState.queryAppUsagePriorityGroup(bundleName).then( res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( err => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); }); -// Promise without bundleName +// Promise mode when bundleName is not specified bundleState.queryAppUsagePriorityGroup().then( res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( err => { @@ -597,7 +597,7 @@ bundleState.queryAppUsagePriorityGroup().then( res => { queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void -Queries the priority group of the current application . This API uses an asynchronous callback to return the result. +Queries the priority group of this application. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO @@ -609,7 +609,7 @@ Queries the priority group of the current application . This API uses an asynchr | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the result. | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | **Example** @@ -639,8 +639,8 @@ Queries the priority group of the application specified by **bundleName**. This | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the target application.| -| callback | AsyncCallback<number> | Yes | Callback used to return the result. | +| bundleName | string | Yes | Bundle name of the target application.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | **Example** @@ -678,7 +678,7 @@ Sets the group for the application specified by **bundleName**. This API uses a | Type | Description | | ------------- | ------------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result. | **Example** @@ -711,7 +711,7 @@ Sets the group for the application specified by **bundleName**. This API uses an | ---------- | ------------------- | ---- | ------------------------- | | bundleName | string | Yes | Bundle name of an application. | | newGroup | [GroupType](#grouptype) | Yes | Application group. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -750,7 +750,7 @@ Registers a callback for application group changes. When an application group of | Type | Description | | ------------- | ----------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result. | **Example** @@ -827,7 +827,7 @@ Deregisters the callback for application group changes. This API uses a promise | Type | Description | | ------------- | ------------------------ | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result. | **Example** @@ -892,7 +892,7 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result. | **Example** @@ -923,7 +923,7 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result. | **Example** @@ -961,7 +961,7 @@ Queries the number of notifications from all applications based on the specified | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result. | **Example** @@ -992,7 +992,7 @@ Queries the number of notifications from all applications based on the specified | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result. | **Example** @@ -1012,6 +1012,8 @@ Provides the information about the FA usage. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ----------------------------- | | deviceId | string | No | ID of the device to which the FA belongs. | @@ -1033,6 +1035,8 @@ Provides the FA widget usage information. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Mandatory | Description | | ---------------- | ------ | ---- | ----------- | | formName | string | Yes | Widget name. | @@ -1047,6 +1051,8 @@ Provides the application group changes returned through a callback. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Mandatory| Description | | ---------------- | ------ | ---- | ---------------- | | appUsageOldGroup | number | Yes | Application group before the change.| @@ -1135,6 +1141,8 @@ Enumerates the application group types. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Default Value | Description | | ------------------ | ---- | ----------------- | | ACTIVE_GROUP_ALIVE | 10 | Group of active applications. | diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 6398b87f685e5f91c59dacb1da97b4ad993e5afa..0bc6f9c6a4c156cfa2d604885572fcbe4bdc41bc 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -16,19 +16,6 @@ import emitter from '@ohos.events.emitter' None -## EventPriority - -Enumerates the event emit priority levels. - -**System capability**: SystemCapability.Notification.Emitter - -| Name | Value | Description | -| --------- | ---- | ------------------------------------------------- | -| IMMEDIATE | 0 | The event will be emitted immediately. | -| HIGH | 1 | The event will be emitted before low-priority events. | -| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority. | -| IDLE | 3 | The event will be emitted after all the other events. | - ## emitter.on on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata)\>): void @@ -39,21 +26,21 @@ Subscribes to an event in persistent manner. This API uses a callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('callback'); -}; -emitter.on(innerEvent, callback); +} +emitter.on(innerEvent, EmitterCallback); ``` ## emitter.once @@ -66,21 +53,21 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('once callback'); }; -emitter.once(innerEvent, callback); +emitter.once(innerEvent, EmitterCallback); ``` ## emitter.off @@ -121,18 +108,31 @@ Emits an event to the event queue. **Example** ```javascript -var eventData = { +let eventData = { data: { "content": "c", "id": 1, }}; -var innerEvent = { +let innerEvent = { eventId: 1, priority: emitter.EventPriority.HIGH }; emitter.emit(innerEvent, eventData); ``` +## EventPriority + +Enumerates the event emit priority levels. + +**System capability**: SystemCapability.Notification.Emitter + +| Name | Value | Description | +| --------- | ---- | --------------------------------------------------- | +| IMMEDIATE | 0 | The event will be emitted immediately. | +| HIGH | 1 | The event will be emitted before low-priority events. | +| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority.| +| IDLE | 3 | The event will be emitted after all the other events. | + ## InnerEvent Describes an in-process event. @@ -141,7 +141,7 @@ Describes an in-process event. | Name | Type | Readable| Writable| Description | | -------- | ------------------------------- | ---- | ---- | ---------------------------------- | -| eventId | number | Yes | Yes | Event ID, which is used to identify an event.| +| eventId | number | Yes | Yes | Event ID.| | priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event. | ## EventData diff --git a/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md b/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md index 3158ba2e321cc4c609c70d4ec8ba402c7290b4a4..ce89c3498f39deffd41ccb5ffd318b7cecef8c6f 100644 --- a/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md +++ b/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md @@ -24,7 +24,7 @@ enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { ## DeviceSettingsManager.setDateTime -setDateTime(admin: Want, time: number, callback: AsyncCallback): void +setDateTime(admin: Want, time: number, callback: AsyncCallback\): void Sets the system time. This API uses an asynchronous callback to return the result. @@ -38,7 +38,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application.| | time | number | Yes| Timestamp (ms).| -| callback | AsyncCallback | Yes| Callback used to the result. If the system time is set successfully, **err** is **null**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes| Callback used to the result. If the system time is set successfully, **err** is **null**; otherwise, **err** is an error object.| **Example** @@ -64,7 +64,7 @@ enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { ## DeviceSettingsManager.setDateTime -setDateTime(admin: Want, time: number): Promise +setDateTime(admin: Want, time: number): Promise\ Sets the system time. This API uses a promise to return the result. @@ -83,8 +83,7 @@ Sets the system time. This API uses a promise to return the result. | Type | Description | | ----- | ----------------------------------- | -| Promise | Promise that returns no value.| - +| Promise\ | Promise that returns no value.| **Example** 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 7d7b21f2cb04fbb7c0cb9d9a3581e09813cd00ef..4f97f1d265daaad6cf6b908a158c3154157eed92 100644 --- a/en/application-dev/reference/apis/js-apis-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-extension-context.md @@ -2,12 +2,12 @@ The **ExtensionContext** module, inherited from **Context**, implements the context for Extension abilities. -This module allows access to Extension abilities. +This module provides APIs for accessing resources of a specific Extension ability. An Extension ability can use the context directly provided by **ExtensionContext** or that extended from **ExtensionContext**. For example, **ServiceExtension** uses **[ServiceExtensionContext](js-apis-service-extension-context.md)**, which extends the capabilities of starting, stopping, binding, and unbinding abilities based on **ExtensionContext**. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module can be used only in the stage model. ## Attributes @@ -15,6 +15,99 @@ This module allows access to Extension abilities. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP. | -| config | Configuration | Yes| No| Module configuration information.| -| extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) | Yes| No| Extension ability information.| +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the HAP file
(See **api\bundle\hapModuleInfo.d.ts** in the **SDK** directory.) | +| config | Configuration | Yes| No| Module configuration information.
(See **api\@ohos.application.Configuration.d.ts** in the **SDK** directory.)| +| extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) | Yes| No| Extension ability information.
(See **api\bundle\extensionAbilityInfo.d.ts** in the **SDK** directory.)| + +## When to Use +**ExtensionContext** provides information about an Extension ability, module, and HAP file. You can use the information based on service requirements. The following uses **ServiceExtension** as an example to describe a use case of **ExtensionContext**. + +**Scenario description** +To adapt to devices with different performance, an application provides three modules: highPerformance, midPerformance, and lowPerformance. Each of them provides a Service Extension ability for the entry. During application installation, the application market installs the HAP file of the entry and the HAP file of the module that matches the device performance. During application running, the entry parses **ServiceExtensionContext.HapModuleInfo** to obtain the HAP file information and executes service logic based on this file. + +![Example](figures/en_us_image_ExtensionContext_Example.png) + +**Example** + +Define a **ServiceExtension** with the same name for the three modules. +``` js +import ServiceExtension from '@ohos.application.ServiceExtensionAbility' +import Want from '@ohos.application.Want' +export default class TheServiceExtension extends ServiceExtension { + onCreate(want:Want) { + console.log('ServiceAbility onCreate, want: ' + want.abilityName); + // Pass ExtensionContext to entry via globalThis. + globalThis.ExtensionContext = this.context; + } + + onRequest(want, startId) { + console.log('ServiceAbility onRequest, want: ' + want.abilityName + ', startId: ' + startId); + } + + onConnect(want) { + console.log('ServiceAbility onConnect, want:' + want.abilityName); + return null; + } + + onDisconnect(want) { + console.log('ServiceAbility onDisconnect, want:' + want.abilityName); + } + + onDestroy() { + console.log('ServiceAbility onDestroy'); + } +}; +``` + +Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry. +``` js +import Ability from '@ohos.application.Ability' +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[Demo] MainAbility onCreate"); + let wantExt = { + deviceId: "", + bundleName: "com.example.TheServiceExtension", + abilityName: "TheServiceExtension", + }; + this.context.startServiceExtensionAbility(wantExt); + } +}; +``` + +Create a **ServiceModule.ts** file in the entry to execute service logic. +``` js +export default class ServiceModel { + moduleName: string; + + constructor() {} + + executeTask() { + if (globalThis.ExtensionContext == undefined) { + console.log("ERROR, ServiceExtension does not exist"); + return; + } + + var moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; + this.moduleName = moduleInfo.name; + // Execute service logic based on the module name, which differentiates devices with different performance. + switch (this.moduleName) { + case "highPerformance": + console.log("This is high performance device."); + // Execute the corresponding service logic. + break; + case "midPerformance": + console.log("This is mid performance device."); + // Execute the corresponding service logic. + break; + case "lowPerformance": + console.log("This is low performance device."); + // Execute the corresponding service logic. + break; + default: + console.log("ERROR, invalid moduleName."); + break; + } + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 4d3791fd26788b92c136c32df7f298787f887f3d..8a55647849f7b2633a7b69e6fc5ff49f4a20f1e6 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -1,6 +1,6 @@ # File Management -The fileio module provides APIs for file storage and management, including basic file management, directory management, file information statistics, and stream read and write. +The **fileio** module provides APIs for file storage and management, including basic file management, directory management, file information statistics, and stream read and write. > **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. @@ -24,7 +24,7 @@ import Ability from '@ohos.application.Ability'; class MainAbility extends Ability { onWindowStageCreate(windowStage) { let context = this.context; - let path = context.filesDir; + let pathDir = context.filesDir; } } ``` @@ -37,7 +37,7 @@ FA Model import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); context.getFilesDir().then((data) => { - let path = data; + let pathDir = data; }) ``` @@ -66,7 +66,8 @@ Obtains file information. This API uses a promise to return the result. **Example** ```js - fileio.stat(path).then(function(stat){ + let filePath = pathDir + "test.txt"; + fileio.stat(filePath).then(function(stat){ console.info("Got file info:"+ JSON.stringify(stat)); }).catch(function(err){ console.info("Failed to get file info. Error:"+ err); @@ -76,7 +77,7 @@ Obtains file information. This API uses a promise to return the result. ## fileio.stat -stat(path:string, callback:AsyncCallback<Stat>): void +stat(path: string, callback: AsyncCallback<Stat>): void Obtains file information. This API uses an asynchronous callback to return the result. @@ -92,7 +93,7 @@ Obtains file information. This API uses an asynchronous callback to return the r **Example** ```js - fileio.stat(path, function (err, stat) { + fileio.stat(pathDir, function (err, stat) { // Example code in Stat }); ``` @@ -100,7 +101,7 @@ Obtains file information. This API uses an asynchronous callback to return the r ## fileio.statSync -statSync(path:string): Stat +statSync(path: string): Stat Synchronously obtains file information. @@ -122,7 +123,7 @@ Synchronously obtains file information. **Example** ```js - let stat = fileio.statSync(path); + let stat = fileio.statSync(pathDir); // Example code in Stat ``` @@ -150,7 +151,8 @@ Opens a file directory. This API uses a promise to return the result. **Example** ```js - fileio.opendir(path).then(function(dir){ + let dirPath = pathDir + "/testDir"; + fileio.opendir(dirPath).then(function(dir){ console.info("Directory opened:"+ JSON.stringify(dir)); }).catch(function(err){ console.info("Failed to open the directory. Error:"+ err); @@ -176,7 +178,7 @@ Opens a file directory. This API uses an asynchronous callback to return the res **Example** ```js - fileio.opendir(path, function (err, dir) { + fileio.opendir(pathDir, function (err, dir) { // Example code in Dir struct // Use read/readSync/close. }); @@ -207,7 +209,7 @@ Synchronously opens a directory. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); // Example code in Dir struct // Use read/readSync/close. ``` @@ -237,7 +239,8 @@ Checks whether the current process can access a file. This API uses a promise to **Example** ```js - fileio.access(path).then(function() { + let filePath = pathDir + "/test.txt"; + fileio.access(filePath).then(function() { console.info("Access successful"); }).catch(function(err){ console.info("Access failed. Error:"+ err); @@ -264,7 +267,8 @@ Checks whether the current process can access a file. This API uses an asynchron **Example** ```js - fileio.access(path, function (err) { + let filePath = pathDir + "/test.txt"; + fileio.access(filePath, function (err) { // Do something. }); ``` @@ -288,17 +292,18 @@ Synchronously checks whether the current process can access the specified file. **Example** ```js + let filePath = pathDir + "/test.txt"; try { - fileio.accessSync(path); + fileio.accessSync(filePath); } catch(err) { - console.info("accessSync failed. Error:"+ err); + console.info("accessSync failed with error:"+ err); } ``` ## fileio.close7+ -close(fd: number):Promise<void> +close(fd: number): Promise<void> Closes a file. This API uses a promise to return the result. @@ -319,7 +324,8 @@ Closes a file. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.close(fd).then(function(){ console.info("File closed"); }).catch(function(err){ @@ -330,7 +336,7 @@ Closes a file. This API uses a promise to return the result. ## fileio.close7+ -close(fd: number, callback:AsyncCallback<void>): void +close(fd: number, callback: AsyncCallback<void>): void Closes a file. This API uses an asynchronous callback to return the result. @@ -346,7 +352,8 @@ Closes a file. This API uses an asynchronous callback to return the result. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.close(fd, function (err) { // Do something. }); @@ -370,14 +377,15 @@ Synchronously closes a file. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.closeSync(fd); ``` ## fileio.copyFile -copyFile(src:string | number, dest:string | number, mode?:number):Promise<void> +copyFile(src: string | number, dest: string | number, mode?: number): Promise<void> Copies a file. This API uses a promise to return the result. @@ -400,9 +408,9 @@ Copies a file. This API uses a promise to return the result. **Example** ```js - let src = path; - let dest = src + 'tgt'; - fileio.copyFile(src, dest).then(function(){ + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fileio.copyFile(srcPath, dstPath).then(function(){ console.info("File copied"); }).catch(function(err){ console.info("Failed to copy the file. Error:"+ err); @@ -430,9 +438,9 @@ Copies a file. This API uses an asynchronous callback to return the result. **Example** ```js - let src = path; - let dest = src + 'tgt'; - fileio.copyFile(src, dest, function (err) { + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fileio.copyFile(srcPath, dstPath, function (err) { // Do something. }); ``` @@ -457,15 +465,15 @@ Synchronously copies a file. **Example** ```js - let src = path; - let dest = src + 'tgt'; - fileio.copyFileSync(src, dest); + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fileio.copyFileSync(srcPath, dstPath); ``` ## fileio.mkdir -mkdir(path:string, mode?: number): Promise<void> +mkdir(path: string, mode?: number): Promise<void> Creates a directory. This API uses a promise to return the result. @@ -487,7 +495,8 @@ Creates a directory. This API uses a promise to return the result. **Example** ```js - fileio.mkdir(path).then(function() { + let dirPath = pathDir + '/testDir'; + fileio.mkdir(dirPath).then(function() { console.info("Directory created"); }).catch(function (error){ console.info("Failed to create the directory. Error:"+ error); @@ -514,7 +523,8 @@ Creates a directory. This API uses an asynchronous callback to return the result **Example** ```js - fileio.mkdir(path, function(err) { + let dirPath = pathDir + '/testDir'; + fileio.mkdir(dirPath, function(err) { console.info("Directory created"); }); ``` @@ -538,7 +548,8 @@ Synchronously creates a directory. **Example** ```js - fileio.mkdirSync(path); + let dirPath = path + '/testDir'; + fileio.mkdirSync(dirPath); ``` @@ -567,7 +578,8 @@ Opens a file. This API uses a promise to return the result. **Example** ```js - fileio.open(path, 0o1, 0o0200).then(function(number){ + let filePath = pathDir + "/test.txt"; + fileio.open(filePath, 0o1, 0o0200).then(function(number){ console.info("File opened"); }).catch(function(err){ console.info("Failed to open the file. Error:"+ err); @@ -588,14 +600,15 @@ Opens a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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** does not point 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.| +| 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** does not point 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.| | callback | AsyncCallback <void> | Yes | Callback invoked when the file is open asynchronously. | **Example** ```js - fileio.open(path, 0, function(err, fd) { + let filePath = pathDir + "/test.txt"; + fileio.open(filePath, 0, function(err, fd) { // Do something. }); ``` @@ -603,7 +616,7 @@ Opens a file. This API uses an asynchronous callback to return the result. ## fileio.openSync -openSync(path:string, flags?:number, mode?:number): number +openSync(path: string, flags?: number, mode?: number): number Synchronously opens a file. @@ -626,12 +639,14 @@ Synchronously opens a file. **Example** ```js - let fd = fileio.openSync(path, 0o102, 0o640); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o102, 0o640); ``` ```js - let fd = fileio.openSync(path, 0o102, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o102, 0o666); fileio.writeSync(fd, 'hello world'); - let fd1 = fileio.openSync(path, 0o2002); + let fd1 = fileio.openSync(filePath, 0o2002); fileio.writeSync(fd1, 'hello world'); let num = fileio.readSync(fd1, new ArrayBuffer(4096), {position: 0}); console.info("num == " + num); @@ -667,7 +682,8 @@ Reads data from a file. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path, 0o2); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o2); let buf = new ArrayBuffer(4096); fileio.read(fd, buf).then(function(readOut){ console.info("Read file data successfully"); @@ -702,7 +718,8 @@ Reads data from a file. This API uses an asynchronous callback to return the res **Example** ```js - let fd = fileio.openSync(path, 0o2); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o2); let buf = new ArrayBuffer(4096); fileio.read(fd, buf, function (err, readOut) { if (readOut) { @@ -742,7 +759,8 @@ Synchronously reads data from a file. **Example** ```js - let fd = fileio.openSync(path, 0o2); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o2); let buf = new ArrayBuffer(4096); let num = fileio.readSync(fd, buf); ``` @@ -771,7 +789,8 @@ Deletes a directory. This API uses a promise to return the result. **Example** ```js - fileio.rmdir(path).then(function() { + let dirPath = pathDir + '/testDir'; + fileio.rmdir(dirPath).then(function() { console.info("Directory deleted"); }).catch(function(err){ console.info("Failed to delete the directory. Error:"+ err); @@ -781,7 +800,7 @@ Deletes a directory. This API uses a promise to return the result. ## fileio.rmdir7+ -rmdir(path: string, callback:AsyncCallback<void>): void +rmdir(path: string, callback: AsyncCallback<void>): void Deletes a directory. This API uses an asynchronous callback to return the result. @@ -797,7 +816,8 @@ Deletes a directory. This API uses an asynchronous callback to return the result **Example** ```js - fileio.rmdir(path, function(err){ + let dirPath = pathDir + '/testDir'; + fileio.rmdir(dirPath, function(err){ // Do something. console.info("Directory deleted"); }); @@ -821,13 +841,14 @@ Synchronously deletes a directory. **Example** ```js - fileio.rmdirSync(path); + let dirPath = pathDir + '/testDir'; + fileio.rmdirSync(dirPath); ``` ## fileio.unlink -unlink(path:string): Promise<void> +unlink(path: string): Promise<void> Deletes a file. This API uses a promise to return the result. @@ -848,7 +869,8 @@ Deletes a file. This API uses a promise to return the result. **Example** ```js - fileio.unlink(path).then(function(){ + let filePath = pathDir + "/test.txt"; + fileio.unlink(filePath).then(function(){ console.info("File deleted"); }).catch(function(error){ console.info("Failed to delete the file. Error:"+ error); @@ -858,7 +880,7 @@ Deletes a file. This API uses a promise to return the result. ## fileio.unlink -unlink(path:string, callback:AsyncCallback<void>): void +unlink(path: string, callback: AsyncCallback<void>): void Deletes a file. This API uses an asynchronous callback to return the result. @@ -874,7 +896,8 @@ Deletes a file. This API uses an asynchronous callback to return the result. **Example** ```js - fileio.unlink(path, function(err) { + let filePath = pathDir + "/test.txt"; + fileio.unlink(filePath, function(err) { console.info("File deleted"); }); ``` @@ -897,7 +920,8 @@ Synchronously deletes a file. **Example** ```js - fileio.unlinkSync(path); + let filePath = pathDir + "/test.txt"; + fileio.unlinkSync(filePath); ``` @@ -931,7 +955,8 @@ Writes data into a file. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world").then(function(number){ console.info("Data written to the file. Size is:"+ number); }).catch(function(err){ @@ -965,7 +990,8 @@ Writes data into a file. This API uses an asynchronous callback to return the re **Example** ```js - let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (bytesWritten) { console.info("Data written to the file. Size is:"+ bytesWritten); @@ -1004,7 +1030,8 @@ Synchronously writes data into a file. **Example** ```js - let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); let num = fileio.writeSync(fd, "hello, world"); ``` @@ -1033,7 +1060,8 @@ Calculates the hash value of a file. This API uses a promise to return the resul **Example** ```js - fileio.hash(path, "sha256").then(function(str){ + let filePath = pathDir + "/test.txt"; + fileio.hash(filePath, "sha256").then(function(str){ console.info("Calculated file hash:"+ str); }).catch(function(err){ console.info("Failed to calculate the file hash. Error:"+ err); @@ -1060,7 +1088,8 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r **Example** ```js - fileio.hash(path, "sha256", function(err, hashStr) { + let filePath = pathDir + "/test.txt"; + fileio.hash(filePath, "sha256", function(err, hashStr) { if (hashStr) { console.info("Calculated file hash:"+ hashStr); } @@ -1070,7 +1099,7 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r ## fileio.chmod7+ -chmod(path: string, mode: number):Promise<void> +chmod(path: string, mode: number): Promise<void> Changes file permissions. This API uses a promise to return the result. @@ -1092,7 +1121,8 @@ Changes file permissions. This API uses a promise to return the result. **Example** ```js - fileio.chmod(path, 0o700).then(function() { + let filePath = pathDir + "/test.txt"; + fileio.chmod(filePath, 0o700).then(function() { console.info("File permissions changed"); }).catch(function(err){ console.info("Failed to change file permissions. Error:"+ err); @@ -1119,7 +1149,8 @@ Changes file permissions. This API uses an asynchronous callback to return the r **Example** ```js - fileio.chmod(path, 0o700, function (err) { + let filePath = pathDir + "/test.txt"; + fileio.chmod(filePath, 0o700, function (err) { // Do something. }); ``` @@ -1143,7 +1174,8 @@ Synchronously changes file permissions. **Example** ```js - fileio.chmodSync(path, 0o700); + let filePath = pathDir + "/test.txt"; + fileio.chmodSync(filePath, 0o700); ``` @@ -1170,7 +1202,8 @@ Obtains file information based on the file descriptor. This API uses a promise t **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fstat(fd).then(function(stat){ console.info("Obtained file info:"+ JSON.stringify(stat)); }).catch(function(err){ @@ -1197,7 +1230,8 @@ Obtains file information based on the file descriptor. This API uses an asynchro **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fstat(fd, function (err) { // Do something. }); @@ -1227,7 +1261,8 @@ Synchronously obtains file information based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let stat = fileio.fstatSync(fd); ``` @@ -1256,7 +1291,8 @@ Truncates a file based on the file descriptor. This API uses a promise to return **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.ftruncate(fd, 5).then(function(err) { console.info("File truncated"); }).catch(function(err){ @@ -1267,7 +1303,7 @@ Truncates a file based on the file descriptor. This API uses a promise to return ## fileio.ftruncate7+ -ftruncate(fd: number, len: number, callback:AsyncCallback<void>): void +ftruncate(fd: number, len: number, callback: AsyncCallback<void>): void Truncates a file based on the file descriptor. This API uses an asynchronous callback to return the result. @@ -1278,13 +1314,14 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal | 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 that returns no value.| + | len | number | No | File length, in bytes, after truncation.| + | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let len = 5; fileio.ftruncate(fd, 5, function(err){ // Do something. @@ -1310,7 +1347,8 @@ Synchronously truncates a file based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let len = 5; fileio.ftruncateSync(fd, len); ``` @@ -1340,8 +1378,9 @@ Truncates a file based on the file path. This API uses a promise to return the r **Example** ```js + let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncate(path, len).then(function(){ + fileio.truncate(filePath, len).then(function(){ console.info("File truncated"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); @@ -1351,7 +1390,7 @@ Truncates a file based on the file path. This API uses a promise to return the r ## fileio.truncate7+ -truncate(path: string, len: number, callback:AsyncCallback<void>): void +truncate(path: string, len: number, callback: AsyncCallback<void>): void Truncates a file based on the file path. This API uses an asynchronous callback to return the result. @@ -1362,14 +1401,15 @@ Truncates a file based on the file path. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------- | | path | string | Yes | Application sandbox path of the file to truncate.| -| len | number | Yes | File length, in bytes, after truncation.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| +| len | number | No | File length, in bytes, after truncation.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** ```js + let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncate(path, len, function(err){ + fileio.truncate(filePath, len, function(err){ // Do something. }); ``` @@ -1393,8 +1433,9 @@ Synchronously truncates a file based on the file path. **Example** ```js + let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncateSync(path, len); + fileio.truncateSync(filePath, len); ``` @@ -1426,7 +1467,8 @@ Reads the text content of a file. This API uses a promise to return the result. **Example** ```js - fileio.readText(path).then(function(str) { + let filePath = pathDir + "/test.txt"; + fileio.readText(filePath).then(function(str) { console.info("Read text successfully:"+ str); }).catch(function(err){ console.info("Failed to read the text. Error:"+ err); @@ -1451,13 +1493,14 @@ Reads the text content of a file. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | -| options | Object | Yes | 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**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| +| 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**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| | callback | AsyncCallback<string> | Yes | Callback used to return the content read. | **Example** ```js - fileio.readText(path, { position: 1, encoding: 'UTF-8' }, function(err, str){ + let filePath = pathDir + "/test.txt"; + fileio.readText(filePath, { position: 1, encoding: 'UTF-8' }, function(err, str){ // Do something. }); ``` @@ -1491,7 +1534,8 @@ Synchronously reads the text of a file. **Example** ```js - let str = fileio.readTextSync(path, {position: 1, length: 3}); + let filePath = pathDir + "/test.txt"; + let str = fileio.readTextSync(filePath, {position: 1, length: 3}); ``` @@ -1518,8 +1562,9 @@ Obtains link information. This API uses a promise to return the result. **Example** ```js - fileio.lstat(path).then(function(stat){ - console.info("Got link info:"+ JSON.stringify(stat)); + let filePath = pathDir + "/test.txt"; + fileio.lstat(filePath).then(function(stat){ + console.info("Get link info:"+ JSON.stringify(stat)); }).catch(function(err){ console.info("Failed to obtain link info. Error:"+ err); }); @@ -1528,7 +1573,7 @@ Obtains link information. This API uses a promise to return the result. ## fileio.lstat7+ -lstat(path:string, callback:AsyncCallback<Stat>): void +lstat(path: string, callback: AsyncCallback<Stat>): void Obtains link information. This API uses an asynchronous callback to return the result. @@ -1544,7 +1589,8 @@ Obtains link information. This API uses an asynchronous callback to return the r **Example** ```js - fileio.lstat(path, function (err, stat) { + let filePath = pathDir + "/test.txt"; + fileio.lstat(filePath, function (err, stat) { // Do something. }); ``` @@ -1552,7 +1598,7 @@ Obtains link information. This API uses an asynchronous callback to return the r ## fileio.lstatSync7+ -lstatSync(path:string): Stat +lstatSync(path: string): Stat Synchronously obtains the link information. @@ -1573,7 +1619,8 @@ Synchronously obtains the link information. **Example** ```js - let stat = fileio.lstatSync(path); + let filePath = pathDir + "/test.txt"; + let stat = fileio.lstatSync(filePath); ``` @@ -1601,9 +1648,9 @@ Renames a file. This API uses a promise to return the result. **Example** ```js - let oldPath = path; - let newPath = oldPath + '123'; - fileio.rename(oldPath, newPath).then(function() { + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fileio.rename(srcFile, dstFile).then(function() { console.info("File renamed"); }).catch(function(err){ console.info("Failed to rename the file. Error:"+ err); @@ -1630,9 +1677,9 @@ Renames a file. This API uses an asynchronous callback to return the result. **Example** ```js - let oldPath = path; - let newPath = oldPath + '123'; - fileio.rename(oldPath, newPath, function(err){ + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fileio.rename(srcFile, dstFile, function(err){ }); ``` @@ -1655,9 +1702,9 @@ Synchronously renames a file. **Example** ```js - let oldPath = path; - let newPath = oldPath + '123'; - fileio.renameSync(oldPath, newPath); + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fileio.renameSync(srcFile, dstFile); ``` @@ -1684,7 +1731,8 @@ Flushes data of a file to disk. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fsync(fd).then(function(){ console.info("Data flushed"); }).catch(function(err){ @@ -1711,7 +1759,8 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fsync(fd, function(err){ // Do something. }); @@ -1735,7 +1784,8 @@ Flushes data of a file to disk in synchronous mode. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fsyncSync(fd); ``` @@ -1763,7 +1813,8 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdatasync(fd).then(function(err) { console.info("Data flushed"); }).catch(function(err){ @@ -1774,7 +1825,7 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** ## fileio.fdatasync7+ -fdatasync(fd: number, callback:AsyncCallback<void>): void +fdatasync(fd: number, callback: AsyncCallback<void>): void Flushes data of a file to disk. This API uses an asynchronous callback to return the result. @@ -1790,7 +1841,8 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdatasync (fd, function (err) { // Do something. }); @@ -1814,7 +1866,8 @@ Synchronizes data in a file in synchronous mode. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let stat = fileio.fdatasyncSync(fd); ``` @@ -1843,9 +1896,9 @@ Creates a symbolic link based on the file path. This API uses a promise to retur **Example** ```js - let target = path; - let srcPath = target + 'aaa'; - fileio.symlink(target, srcPath).then(function() { + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fileio.symlink(srcFile, dstFile).then(function() { console.info("Symbolic link created"); }).catch(function(err){ console.info("Failed to create the symbolic link. Error:"+ err); @@ -1872,9 +1925,9 @@ Creates a symbolic link based on the file path. This API uses an asynchronous ca **Example** ```js - let target = path; - let srcPath = target + 'aaa'; - fileio.symlink(target, srcPath, function (err) { + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fileio.symlink(srcFile, dstFile, function (err) { // Do something. }); ``` @@ -1898,9 +1951,9 @@ Synchronously creates a symbolic link based on a specified path. **Example** ```js - let target = path; - let srcPath = target + 'aaa'; - fileio.symlinkSync(target, srcPath); + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fileio.symlinkSync(srcFile, dstFile); ``` @@ -1929,8 +1982,9 @@ Changes the file owner based on the file path. This API uses a promise to return **Example** ```js - let stat = fileio.statSync(path); - fileio.chown(path, stat.uid, stat.gid).then(function(){ + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.chown(filePath, stat.uid, stat.gid).then(function(){ console.info("File owner changed"); }).catch(function(err){ console.info("Failed to change the file owner. Error:"+ err); @@ -1958,8 +2012,9 @@ Changes the file owner based on the file path. This API uses an asynchronous cal **Example** ```js - let stat = fileio.statSync(path) - fileio.chown(path, stat.uid, stat.gid, function (err){ + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath) + fileio.chown(filePath, stat.uid, stat.gid, function (err){ // Do something. }); ``` @@ -1984,8 +2039,9 @@ Synchronously changes the file owner based on its path. **Example** ```js - let stat = fileio.statSync(path) - fileio.chownSync(path, stat.uid, stat.gid); + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath) + fileio.chownSync(filePath, stat.uid, stat.gid); ``` @@ -2012,8 +2068,8 @@ Creates a temporary directory. This API uses a promise to return the result. **Example** ```js - fileio.mkdtemp(path + "XXXX").then(function(path){ - console.info("Temporary directory created:"+ path); + fileio.mkdtemp(pathDir + "/XXXXXX").then(function(pathDir){ + console.info("mkdtemp succeed:"+ pathDir); }).catch(function(err){ console.info("Failed to create the temporary directory. Error:"+ err); }); @@ -2038,7 +2094,7 @@ Creates a temporary directory. This API uses an asynchronous callback to return **Example** ```js - fileio.mkdtemp(path + "XXXX", function (err, res) { + fileio.mkdtemp(pathDir + "/XXXXXX", function (err, res) { // Do something. }); ``` @@ -2067,7 +2123,7 @@ Synchronously creates a temporary directory. **Example** ```js - let res = fileio.mkdtempSync(path + "XXXX"); + let res = fileio.mkdtempSync(pathDir + "/XXXXXX"); ``` @@ -2095,7 +2151,8 @@ Changes file permissions based on the file descriptor. This API uses a promise t **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let mode = 0o700; fileio.fchmod(fd, mode).then(function() { console.info("File permissions changed"); @@ -2124,7 +2181,8 @@ Changes file permissions based on the file descriptor. This API uses an asynchro **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let mode = 0o700; fileio.fchmod(fd, mode, function (err) { // Do something. @@ -2150,7 +2208,8 @@ Synchronously changes the file permissions based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let mode = 0o700; fileio.fchmodSync(fd, mode); ``` @@ -2180,8 +2239,9 @@ Opens a file stream based on the file path. This API uses a promise to return th **Example** ```js - fileio.createStream(path, "r+").then(function(stream){ - console.info("Stream opened"); + let filePath = pathDir + "/test.txt"; + fileio.createStream(filePath, "r+").then(function(stream){ + console.info("Stream created"); }).catch(function(err){ console.info("Failed to create the stream. Error:"+ err); }); @@ -2207,7 +2267,8 @@ Opens a file stream based on the file path. This API uses an asynchronous callba **Example** ```js - fileio.createStream(path, "r+", function(err, stream){ + let filePath = pathDir + "/test.txt"; + fileio.createStream(filePath, "r+", function(err, stream){ // Do something. }); ``` @@ -2237,7 +2298,8 @@ Synchronously opens a stream based on the file path. **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); ``` @@ -2265,7 +2327,8 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdopenStream(fd, "r+").then(function(stream){ console.info("Stream opened"); }).catch(function(err){ @@ -2293,7 +2356,8 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdopenStream(fd, "r+", function (err, stream) { // Do something. }); @@ -2324,7 +2388,8 @@ Synchronously opens a stream based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let ss = fileio.fdopenStreamSync(fd, "r+"); ``` @@ -2354,8 +2419,9 @@ Changes the file owner based on the file descriptor. This API uses a promise to **Example** ```js - let fd = fileio.openSync(path); - let stat = fileio.statSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); + let stat = fileio.statSync(filePath); fileio.fchown(fd, stat.uid, stat.gid).then(function() { console.info("File owner changed"); }).catch(function(err){ @@ -2384,8 +2450,9 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono **Example** ```js - let fd = fileio.openSync(path); - let stat = fileio.statSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); + let stat = fileio.statSync(filePath); fileio.fchown(fd, stat.uid, stat.gid, function (err){ // Do something. }); @@ -2411,8 +2478,9 @@ Synchronously changes the file owner based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); - let stat = fileio.statSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); + let stat = fileio.statSync(filePath); fileio.fchownSync(fd, stat.uid, stat.gid); ``` @@ -2442,8 +2510,9 @@ Changes the file owner (owner of the symbolic link, not the file referred to by **Example** ```js - let stat = fileio.statSync(path); - fileio.lchown(path, stat.uid, stat.gid).then(function() { + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.lchown(filePath, stat.uid, stat.gid).then(function() { console.info("File owner changed"); }).catch(function(err){ console.info("Failed to change the file owner. Error:"+ err); @@ -2471,8 +2540,9 @@ Changes the file owner (owner of the symbolic link, not the file referred to by **Example** ```js - let stat = fileio.statSync(path); - fileio.lchown(path, stat.uid, stat.gid, function (err){ + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.lchown(filePath, stat.uid, stat.gid, function (err){ // Do something. }); ``` @@ -2497,8 +2567,9 @@ Synchronously changes the file owner based on the file path and changes the owne **Example** ```js - let stat = fileio.statSync(path); - fileio.lchownSync(path, stat.uid, stat.gid); + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.lchownSync(filePath, stat.uid, stat.gid); ``` @@ -2514,7 +2585,7 @@ Listens for file or directory changes. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| filename | string | Yes | Application sandbox path of the file. | +| filePath | string | Yes | Application sandbox path of the 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. | @@ -2527,8 +2598,8 @@ Listens for file or directory changes. This API uses an asynchronous callback to **Example** ```js - let filename = path +"/test.txt"; - fileio.createWatcher(filename, 1, function(number){ + let filePath = pathDir +"/test.txt"; + fileio.createWatcher(filePath, 1, function(number){ console.info("Monitoring times: "+number); }); @@ -2589,7 +2660,8 @@ Checks whether this file is a block special file. A block special file supports **Example** ```js - let isBLockDevice = fileio.statSync(path).isBlockDevice(); + let filePath = pathDir + "/test.txt"; + let isBLockDevice = fileio.statSync(filePath).isBlockDevice(); ``` @@ -2610,7 +2682,8 @@ Checks whether this file is a character special file. A character special file s **Example** ```js - let isCharacterDevice = fileio.statSync(path).isCharacterDevice(); + let filePath = pathDir + "/test.txt"; + let isCharacterDevice = fileio.statSync(filePath).isCharacterDevice(); ``` @@ -2631,7 +2704,8 @@ Checks whether this file is a directory. **Example** ```js - let isDirectory = fileio.statSync(path).isDirectory(); + let dirPath = pathDir + "/test"; + let isDirectory = fileio.statSync(dirPath).isDirectory(); ``` @@ -2652,7 +2726,8 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int **Example** ```js - let isFIFO = fileio.statSync(path).isFIFO(); + let filePath = pathDir + "/test.txt"; + let isFIFO = fileio.statSync(filePath).isFIFO(); ``` @@ -2673,7 +2748,8 @@ Checks whether this file is a regular file. **Example** ```js - let isFile = fileio.statSync(path).isFile(); + let filePath = pathDir + "/test.txt"; + let isFile = fileio.statSync(filePath).isFile(); ``` @@ -2694,7 +2770,8 @@ Checks whether this file is a socket. **Example** ```js - let isSocket = fileio.statSync(path).isSocket(); + let filePath = pathDir + "/test.txt"; + let isSocket = fileio.statSync(filePath).isSocket(); ``` @@ -2715,7 +2792,8 @@ Checks whether this file is a symbolic link. **Example** ```js - let isSymbolicLink = fileio.statSync(path).isSymbolicLink(); + let filePath = pathDir + "/test"; + let isSymbolicLink = fileio.statSync(filePath).isSymbolicLink(); ``` @@ -2735,8 +2813,8 @@ Stops the **watcher** instance. This API uses a promise to return the result. **Example** ```js - let filename = path +"/test.txt"; - let watcher = fileio.createWatcher(filename, 1, function(number){ + let filePath = path + "/test.txt"; + let watcher = fileio.createWatcher(filePath, 1, function(number){ console.info("Monitoring times: "+number); }); watcher.stop().then(function(){ @@ -2762,8 +2840,8 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return **Example** ```js - let filename = path +"/test.txt"; - let watcher = fileio.createWatcher(filename, 1, function(number){ + let filePath = path +"/test.txt"; + let watcher = fileio.createWatcher(filePath, 1, function(number){ console.info("Monitoring times: "+number); }); watcher.stop(function(){ @@ -2771,6 +2849,7 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return }) ``` + ## Stream Provides file stream management. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. @@ -2793,7 +2872,8 @@ Closes the stream. This API uses a promise to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.close().then(function(){ console.info("File stream closed"); }).catch(function(err){ @@ -2819,9 +2899,10 @@ Closes the stream. This API uses an asynchronous callback to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.close(function (err) { - // Do something + // Do something. }); ``` @@ -2837,7 +2918,8 @@ Synchronously closes the stream. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.closeSync(); ``` @@ -2859,7 +2941,8 @@ Flushes the stream. This API uses a promise to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.flush().then(function (){ console.info("Stream flushed"); }).catch(function(err){ @@ -2885,9 +2968,10 @@ Flushes the stream. This API uses an asynchronous callback to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.flush(function (err) { - // Do something + // Do something. }); ``` @@ -2903,7 +2987,8 @@ Synchronously flushes the stream. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.flushSync(); ``` @@ -2937,7 +3022,8 @@ Writes data into the stream. This API uses a promise to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ console.info("Data written to the stream. Size is:"+ number); }).catch(function(err){ @@ -2970,10 +3056,11 @@ Writes data into the stream. This API uses an asynchronous callback to return th **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { if (bytesWritten) { - // Do something + // Do something. console.info("Data written to the stream. Size is:"+ bytesWritten); } }); @@ -3009,7 +3096,8 @@ Synchronously writes data into the stream. **Example** ```js - let ss= fileio.createStreamSync(path,"r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath,"r+"); let num = ss.writeSync("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}); ``` @@ -3042,7 +3130,8 @@ Reads data from the stream. This API uses a promise to return the result. **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readOut){ console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); @@ -3075,7 +3164,8 @@ Reads data from the stream. This API uses an asynchronous callback to return the **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { if (readOut) { console.info("Read data successfully"); @@ -3113,7 +3203,8 @@ Synchronously reads data from the stream. **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); let num = ss.readSync(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}); ``` @@ -3167,7 +3258,7 @@ Reads the next directory entry. This API uses an asynchronous callback to return ```js dir.read(function (err, dirent) { if (dirent) { - // Do something + // Do something. console.log("Read the next directory entry:"+JSON.stringify(dirent)); } }); @@ -3274,7 +3365,7 @@ Checks whether this directory entry is a block special file. A block special fil **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isBLockDevice = dir.readSync().isBlockDevice(); ``` @@ -3296,7 +3387,7 @@ Checks whether a directory entry is a character special file. A character specia **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isCharacterDevice = dir.readSync().isCharacterDevice(); ``` @@ -3318,7 +3409,7 @@ Checks whether a directory entry is a directory. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isDirectory = dir.readSync().isDirectory(); ``` @@ -3340,7 +3431,7 @@ Checks whether this directory entry is a named pipe (or FIFO). Named pipes are u **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isFIFO = dir.readSync().isFIFO(); ``` @@ -3362,7 +3453,7 @@ Checks whether a directory entry is a regular file. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isFile = dir.readSync().isFile(); ``` @@ -3384,7 +3475,7 @@ Checks whether a directory entry is a socket. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isSocket = dir.readSync().isSocket(); ``` @@ -3406,6 +3497,24 @@ Checks whether a directory entry is a symbolic link. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isSymbolicLink = dir.readSync().isSymbolicLink(); ``` + +## Filter9+ + +Defines the file filter configuration. + +**System API**: This is a system API. + +**System capability**: SystemCapability.FileManagement.File.FileIO + + +| Name | Type | Description | +| ----------- | --------------- | ------------------ | +| suffix | Array<string> | File name extensions. The keywords in the array are of the OR relationship. | +| displayName | Array<string> | File name for fuzzy match. The keywords in the array are of the OR relationship.| +| mimeType | Array<string> | MIME types to match. The keywords in the array are of the OR relationship. | +| fileSizeOver | number | File size to match. The files which are of the same or a lager size are matched. | +| lastModifiedAfter | Date | File modification time to match. The files modified after the specified time are matched. | +| excludeMedia | Boolean | Whether to exclude the files already in Media. | diff --git a/en/application-dev/reference/apis/js-apis-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md deleted file mode 100644 index b80660185cffaf10993bf9c54ba1f88a1f16b7f4..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ /dev/null @@ -1,282 +0,0 @@ -# User File Access and Management - -The **fileManager** module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. - ->**NOTE**
-> ->- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**. - -## Modules to Import - -```js -import filemanager from '@ohos.fileManager'; -``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> - -Obtains information about the root album or directory in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<[FileInfo](#fileinfo)[]> | Promise used to return the root album or directory information obtained.| - -**Example** - - ```js - filemanager.getRoot().then((fileInfos) => { - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }).catch((err) => { - console.log(err) - }); - ``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) : void - -Obtains information about the root album or directory in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Example** - - ```js - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.getRoot(options, (err, fileInfos)=>{ - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}) : Promise<FileInfo[]> - -Obtains information about the second-level album or files in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| path | string | Yes| URI of the directory to query.| -| type | string | Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<FileInfo[]> | Promise used to return the album or file information obtained.| - -**Error** - -| Error Info| Error Code|Description| -| -- | --- | -- | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service.| -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Obtain all files in the directory. You can use getRoot to obtain the directory URI. - filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "file_folder"); - let path = file.path; - filemanager.listFile(path, "file").then((files) => { - console.log("files:" + JSON.stringify(files)); - }).catch((err) => { - console.log("failed to get files" + err); - }); - }).catch((err) => { - console.log("failed to get root" + err); - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}, callback : AsyncCallback<FileInfo[]>) : void - -Obtains information about the second-level album or files in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | URI of the directory to query. | -| type | string | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Error** - -| Error Info | Error Code| Description | -| ------------------------- | ------ | ------------------------- | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service. | -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - -```js -// Obtain all files in the directory. You can use getRoot to obtain the directory URI. -filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "image_album"); - let path = file.path; - filemanager.listFile(path, "image",function(err, files){ - console.log("files:" + JSON.stringify(files)); - }) -}).catch((err) => { - console.log("failed to get root" + err); -}); -``` - -## filemanager.createFile - -createFile(path : string, filename : string, options? : {dev? : DevInfo}) : Promise<string> - -Creates a file in the specified path in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| filename | string | Yes| Name of the file to create.| -| path | string | Yes| URI of the file to create.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<string> | Promise used to return the URI of the file created.| - -**Error** - -| Error Info| Error Code|Description| -| -- | --- | -- | -| Operation not permitted | 1 | A file with the same name already exists.| -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service.| -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Create a file. - let media_path = "" // Obtain the file URI using listFile() and getRoot(). - let name = "xxx.jpg" // File to be saved. - filemanager.createFile(media_path, name).then((uri) => { - // The URI of the file created is returned. - console.log("file uri:"+uri); - }).catch((err) => { - console.log(err); - }); - ``` - -## filemanager.createFile - -createFile(path : string, filename: string, options? : {dev? : DevInfo}, callback : AsyncCallback<string>) : void - -Creates a file in the specified path in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| filename | string | Yes | Name of the file to create. | -| path | string | Yes | URI of the file to create. | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Error** - -| Error Info | Error Code| Description | -| ------------------------- | ------ | ------------------------- | -| Operation not permitted | 1 | A file with the same name already exists. | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service. | -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Create a file. - // Call listFile() and getRoot() to obtain the file URI. - let media_path = "" - // File to be saved. - let name = "xxx.jpg" - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.createFile(media_path, name, options, function(err, uri) { - // The URI of the file created is returned. - console.log("file uri:"+uri); - }); - - ``` - -## FileInfo -Defines the file information returned by **getRoot()** or **listFile()**. - -**System capability**: SystemCapability.FileManagement.UserFileService - -### Attributes - -| Name| Type| Readable| Writable| Description| -| --- | -- | -- | -- | -- | -| name | string | Yes| No| File name.| -| path | string | Yes| No| URI of the file.| -| type | string | Yes| No| File type.| -| size | number | Yes| No| File size.| -| addedTime | number | Yes| No| Time when the file was scanned to the database.| -| modifiedTime | number | Yes| No| Time when the file was modified.| - -## DevInfo - -Defines the device type. - -**System capability**: SystemCapability.FileManagement.UserFileService - -### Attributes - -| Name| Type | Readable| Writable| Description | -| ------ | ------ | ---- | ---- | -------- | -| name | string | Yes | Yes | Device name.| diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index f15805a326e19b0a579d1da1ae0e44e9937fef6f..92118167ad603189eac98eae73e156a794542f99 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -14,7 +14,7 @@ import geolocation from '@ohos.geolocation'; ## geolocation.on('locationChange') -on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void Registers a listener for location changes with a location request initiated. @@ -34,6 +34,7 @@ Registers a listener for location changes with a location request initiated. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -44,7 +45,7 @@ Registers a listener for location changes with a location request initiated. ## geolocation.off('locationChange') -off(type: 'locationChange', callback?: Callback<Location>) : void +off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. @@ -63,6 +64,7 @@ Unregisters the listener for location changes with the corresponding location re **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -74,7 +76,7 @@ Unregisters the listener for location changes with the corresponding location re ## geolocation.on('locationServiceState') -on(type: 'locationServiceState', callback: Callback<boolean>) : void +on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. @@ -93,6 +95,7 @@ Registers a listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); } @@ -102,7 +105,7 @@ Registers a listener for location service status change events. ## geolocation.off('locationServiceState') -off(type: 'locationServiceState', callback?: Callback<boolean>) : void; +off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. @@ -121,6 +124,7 @@ Unregisters the listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } @@ -131,7 +135,7 @@ Unregisters the listener for location service status change events. ## geolocation.on('cachedGnssLocationsReporting')8+ -on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; +on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; Registers a listener for cached GNSS location reports. @@ -151,6 +155,7 @@ Registers a listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -161,7 +166,7 @@ Registers a listener for cached GNSS location reports. ## geolocation.off('cachedGnssLocationsReporting')8+ -off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; +off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; Unregisters the listener for cached GNSS location reports. @@ -180,6 +185,7 @@ Unregisters the listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -191,7 +197,7 @@ Unregisters the listener for cached GNSS location reports. ## geolocation.on('gnssStatusChange')8+ -on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; +on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; Registers a listener for GNSS satellite status change events. @@ -210,6 +216,7 @@ Registers a listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -219,7 +226,7 @@ Registers a listener for GNSS satellite status change events. ## geolocation.off('gnssStatusChange')8+ -off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; +off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; Unregisters the listener for GNSS satellite status change events. @@ -237,6 +244,7 @@ Unregisters the listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -247,7 +255,7 @@ Unregisters the listener for GNSS satellite status change events. ## geolocation.on('nmeaMessageChange')8+ -on(type: 'nmeaMessageChange', callback: Callback<string>) : void; +on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. @@ -266,6 +274,7 @@ Registers a listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -275,7 +284,7 @@ Registers a listener for GNSS NMEA message change events. ## geolocation.off('nmeaMessageChange')8+ -off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; +off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. @@ -294,6 +303,7 @@ Unregisters the listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -304,7 +314,7 @@ Unregisters the listener for GNSS NMEA message change events. ## geolocation.on('fenceStatusChange')8+ -on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. @@ -331,13 +341,13 @@ Registers a listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { @@ -349,7 +359,7 @@ Registers a listener for status change events of the specified geofence. ## geolocation.off('fenceStatusChange')8+ -off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. @@ -375,7 +385,7 @@ Unregisters the listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], @@ -392,62 +402,9 @@ Unregisters the listener for status change events of the specified geofence. ``` -## geolocation.on('countryCodeChange')9+ - -on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; - -Subscribe to country code information reporting events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means subscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - ``` - - -## geolocation.off('countryCodeChange')9+ - -off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; - -Unsubscribe from the country code to report events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means unsubscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - geolocation.off('countryCodeChange', callback); - ``` - - ## geolocation.getCurrentLocation -getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void Obtains the current location. This API uses an asynchronous callback to return the result. @@ -466,6 +423,7 @@ Obtains the current location. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { if (err) { @@ -482,7 +440,7 @@ Obtains the current location. This API uses an asynchronous callback to return t ## geolocation.getCurrentLocation -getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> Obtains the current location. This API uses a promise to return the result. @@ -507,6 +465,7 @@ Obtains the current location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); @@ -516,7 +475,7 @@ Obtains the current location. This API uses a promise to return the result. ## geolocation.getLastLocation -getLastLocation(callback: AsyncCallback<Location>) : void +getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. @@ -534,6 +493,7 @@ Obtains the previous location. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { console.log('getLastLocation: err=' + JSON.stringify(err)); @@ -547,7 +507,7 @@ Obtains the previous location. This API uses an asynchronous callback to return ## geolocation.getLastLocation -getLastLocation() : Promise<Location> +getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. @@ -565,6 +525,7 @@ Obtains the previous location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -573,7 +534,7 @@ Obtains the previous location. This API uses a promise to return the result. ## geolocation.isLocationEnabled -isLocationEnabled(callback: AsyncCallback<boolean>) : void +isLocationEnabled(callback: AsyncCallback<boolean>): void Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. @@ -591,6 +552,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { console.log('isLocationEnabled: err=' + JSON.stringify(err)); @@ -604,7 +566,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ## geolocation.isLocationEnabled -isLocationEnabled() : Promise<boolean> +isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. @@ -621,15 +583,16 @@ Checks whether the location service is enabled. This API uses a promise to retur **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { - console.log('promise, isLocationEnabled: ' + result); + console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); }); ``` ## geolocation.requestEnableLocation -requestEnableLocation(callback: AsyncCallback<boolean>) : void +requestEnableLocation(callback: AsyncCallback<boolean>): void Requests to enable the location service. This API uses an asynchronous callback to return the result. @@ -647,6 +610,7 @@ Requests to enable the location service. This API uses an asynchronous callback **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { console.log('requestEnableLocation: err=' + JSON.stringify(err)); @@ -660,7 +624,7 @@ Requests to enable the location service. This API uses an asynchronous callback ## geolocation.requestEnableLocation -requestEnableLocation() : Promise<boolean> +requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. @@ -677,6 +641,7 @@ Requests to enable the location service. This API uses a promise to return the r **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation().then((result) => { console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); @@ -685,7 +650,7 @@ Requests to enable the location service. This API uses a promise to return the r ## geolocation.enableLocation -enableLocation(callback: AsyncCallback<boolean>) : void; +enableLocation(callback: AsyncCallback<boolean>): void; Enables the location service. This API uses an asynchronous callback to return the result. @@ -704,6 +669,7 @@ Enables the location service. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation((err, data) => { if (err) { console.log('enableLocation: err=' + JSON.stringify(err)); @@ -717,7 +683,7 @@ Enables the location service. This API uses an asynchronous callback to return t ## geolocation.enableLocation -enableLocation() : Promise<boolean> +enableLocation(): Promise<boolean> Enables the location service. This API uses a promise to return the result. @@ -736,6 +702,7 @@ Enables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation().then((result) => { console.log('promise, enableLocation: ' + JSON.stringify(result)); }); @@ -743,7 +710,7 @@ Enables the location service. This API uses a promise to return the result. ## geolocation.disableLocation -disableLocation(callback: AsyncCallback<boolean>) : void; +disableLocation(callback: AsyncCallback<boolean>): void; Disables the location service. This API uses an asynchronous callback to return the result. @@ -762,6 +729,7 @@ Disables the location service. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation((err, data) => { if (err) { console.log('disableLocation: err=' + JSON.stringify(err)); @@ -775,7 +743,7 @@ Disables the location service. This API uses an asynchronous callback to return ## geolocation.disableLocation -disableLocation() : Promise<boolean> +disableLocation(): Promise<boolean> Disables the location service. This API uses a promise to return the result. @@ -794,6 +762,7 @@ Disables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation().then((result) => { console.log('promise, disableLocation: ' + JSON.stringify(result)); }); @@ -801,7 +770,7 @@ Disables the location service. This API uses a promise to return the result. ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void +isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. @@ -818,6 +787,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); @@ -831,7 +801,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable() : Promise<boolean> +isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. @@ -848,6 +818,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); @@ -856,7 +827,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. @@ -874,6 +845,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -888,7 +860,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. @@ -911,6 +883,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -920,7 +893,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. @@ -938,6 +911,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -952,7 +926,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. @@ -975,6 +949,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -984,7 +959,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. @@ -1001,6 +976,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); @@ -1014,7 +990,7 @@ Obtains the number of cached GNSS locations. ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize() : Promise<number>; +getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. @@ -1031,6 +1007,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); @@ -1039,7 +1016,7 @@ Obtains the number of cached GNSS locations. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; +flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1056,6 +1033,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); @@ -1069,7 +1047,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations() : Promise<boolean>; +flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1086,6 +1064,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); @@ -1094,7 +1073,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; +sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1112,6 +1091,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1126,7 +1106,7 @@ Sends an extended command to the location subsystem. This API can only be called ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand) : Promise<boolean>; +sendCommand(command: LocationCommand): Promise<boolean>; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1149,6 +1129,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); @@ -1156,826 +1137,182 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## geolocation.isLocationPrivacyConfirmed8+ - -isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; - -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## LocationRequestPriority -**System API**: This is a system API and cannot be called by third-party applications. +Sets the priority of the location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| 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.| - | 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.| -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - if (err) { - console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); - } - if (result) { - console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); - } - }); - ``` +## LocationRequestScenario + + Sets the scenario of the location request. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.isLocationPrivacyConfirmed8+ +| 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.| -isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## GeoLocationErrorCode -**System API**: This is a system API and cannot be called by third-party applications. +Enumerates error codes of the location service. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Default Value| Description| +| -------- | -------- | -------- | +| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| - | 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.| -**Return value** +## ReverseGeoCodeRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| +Defines a reverse geocoding request. -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| 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.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## GeoCodeRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a geocoding request. **Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core +**System capability**: SystemCapability.Location.Location.Geocoder -**Parameters** +| 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.| - | 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| 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** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - if (err) { - console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); - } - if (result) { - console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); - } - }); - ``` +## GeoAddress + +Defines a geographic location. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | No| Landmark of the location.| +| countryCode7+ | string | No| Country code.| +| countryName7+ | string | No| Country name.| +| administrativeArea7+ | string | No| Administrative region name.| +| subAdministrativeArea7+ | string | No| Sub-administrative region name.| +| locality7+ | string | No| Locality information. | +| subLocality7+ | string | No| Sub-locality information. | +| roadName7+ | string | No| Road name.| +| subRoadName7+ | string | No| Auxiliary road information.| +| premises7+ | string | No| House information.| +| postalCode7+ | string | No| Postal code.| +| phoneNumber7+ | string | No| Phone number.| +| addressUrl7+ | string | No| Website URL.| +| descriptions7+ | Array<string> | No| Additional description.| +| descriptionsSize7+ | number | No| Total number of additional descriptions.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## LocationRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| 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.| - | 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| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -**Return value** +## CurrentLocationRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result.| +Defines the current location request. -**Example** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.getCountryCode9+ +| 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.| -getCountryCode(callback: AsyncCallback<CountryCode>) : void; -Query the current country code. +## SatelliteStatusInfo8+ -**System capability**: SystemCapability.Location.Location.Core +Defines the satellite status information. -**Parameters** +**Permission required**: ohos.permission.LOCATION - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<CountryCode> | Yes | Callback is used to receive the country code. | +**System capability**: SystemCapability.Location.Location.Gnss -**Example**: - - ```js - geolocation.getCountryCode((err, result) => { - if (err) { - console.log('getCountryCode: err=' + JSON.stringify(err)); - } - if (result) { - console.log('getCountryCode: result=' + JSON.stringify(result)); - } - }); - ``` +| 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.| -## geolocation.getCountryCode9+ +## CachedGnssLocationsRequest8+ -getCountryCode() : Promise<CountryCode>; +Represents a request for reporting cached GNSS locations. -Query the current country code. +**Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<CountryCode> | return country code. | - -**Example**: - - ```js - geolocation.getCountryCode() - .then((result) => { - console.log('promise, getCountryCode: result=' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, getCountryCode: error=' + JSON.stringify(error)); - }); - ``` - - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates under what scenario the position simulation function is enabled. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request, (err, result) => { - if (err) { - console.log('enableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('enableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates which scene's position simulation function is enabled. If this parameter is not carried, it means that the position simulation function of all scenes is enabled. | - - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request, (err, result) => { - if (err) { - console.log('disableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr, otherwise it will return an error message | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations": locations}; - geolocation.setMockedLocations(config, (err, data) => { - if (err) { - console.log('setMockedLocations: err=' + JSON.stringify(err)); - } - if (data) { - console.log('setMockedLocations: data=' + JSON.stringify(data)); - } - }); - ``` - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig) : Promise<void>; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations":locations}; - geolocation.setMockedLocations(config) - .then((result) => { - if (result) { - console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); - } - }); - ``` - - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock((err, data) => { - if (err) { - console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock() : Promise<void>; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock((err, result) => { - if (err) { - console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock() : Promise<void>; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { - if (err) { - console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); - } - if (data) { - console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos) - .then((result) => { - if (result) { - console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); - } - }); - ``` - - -## LocationRequestPriority - -Sets the priority of the location request. - -**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.| - - -## LocationRequestScenario - - Sets the scenario of the location request. - -**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.| - - -## GeoLocationErrorCode - -Enumerates error codes of the location service. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| NOT_SUPPORTED9+ | 100 | Indicates that the interface function is not supported. | -| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| -| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| -| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| -| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| -| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| -| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| -| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| -| QUERY_COUNTRY_CODE_ERROR9+ | 108 | Indicates that the country code query failed. | - - -## ReverseGeoCodeRequest - -Defines a reverse geocoding request. - -**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.| - - -## GeoCodeRequest - -Defines a geocoding request. - -**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.| - - -## GeoAddress - -Defines a geographic location. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName7+ | string | No| Landmark of the location.| -| countryCode7+ | string | No| Country code.| -| countryName7+ | string | No| Country name.| -| administrativeArea7+ | string | No| Administrative region name.| -| subAdministrativeArea7+ | string | No| Sub-administrative region name.| -| locality7+ | string | No| Locality information. | -| subLocality7+ | string | No| Sub-locality information. | -| roadName7+ | string | No| Road name.| -| subRoadName7+ | string | No| Auxiliary road information.| -| premises7+ | string | No| House information.| -| postalCode7+ | string | No| Postal code.| -| phoneNumber7+ | string | No| Phone number.| -| addressUrl7+ | string | No| Website URL.| -| descriptions7+ | Array<string> | No| Additional description.| -| descriptionsSize7+ | number | No| Total number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the geographical name information comes from the reverse geocoding simulation function. | - - -## LocationRequest - -Defines a location request. - -**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.| - - -## CurrentLocationRequest - -Defines the current location request. - -**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.| - - -## SatelliteStatusInfo8+ - -Defines the satellite status information. - -**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.| - - -## CachedGnssLocationsRequest8+ - -Represents a request for reporting cached GNSS locations. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Gnss +**System capability**: SystemCapability.Location.Location.Gnss | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -2063,58 +1400,3 @@ Defines a location. | timeSinceBoot7+ | number | Yes| Location timestamp since boot.| | additions7+ | Array<string> | No| Additional information.| | additionSize7+ | number | No| Number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the location information comes from the location simulation function. | - - -## ReverseGeocodingMockInfo9+ - -The configuration information of the reverse geocoding simulation function includes a location information and a place name information. - -**System capability**:SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| location | ReverseGeoCodeRequest | Yes | Indicates longitude and latitude information. | -| geoAddress | GeoAddress | Yes | Represents a geographic location. | - - -## LocationMockConfig9+ - -The configuration parameters of the location simulation function include the time interval of the simulation position report and the array of simulation locations. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timeInterval | number | Yes | Indicates the time interval of analog location reporting, in seconds. | -| locations | Array<Location> | Yes | Represents an array of mocked locations. | - - -## CountryCode9+ - -The country code information structure contains the country code string and the source information of the country code. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| country | string | Yes | Represents the country code string. | -| type | CountryCodeType | Yes | Indicates the source of country code information. | - - -## CountryCodeType9+ - -Country code source type. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| COUNTRY_CODE_FROM_LOCALE | 1 | The country code obtained from the language configuration information of the globalization module. | -| COUNTRY_CODE_FROM_SIM | 2 | The country code obtained from the SIM card. | -| COUNTRY_CODE_FROM_LOCATION | 3 | Based on the user's location information, the country code is queried through reverse geocoding. | -| COUNTRY_CODE_FROM_NETWORK | 4 | The country code obtained from the cellular network registration information. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index 9f1110f241e37530914961c21f688e67d44b05af..aefc93a933ecdf42a0d270134d81f17c8a5788af 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -3,6 +3,7 @@ This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. > **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,11 +19,11 @@ Before using application event logging, you need to understand the requirements **Event Domain** -An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Name** -An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Type** @@ -32,7 +33,7 @@ An event type is an enumerated value of [EventType](#eventtype). An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: -- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_). +- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start or end with an underscore (\_). - The parameter value is a string, number, boolean, or array. - When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. @@ -304,11 +305,8 @@ hiAppEvent.addWatcher({ console.error("holder is null"); return; } - while (true) { - let eventPkg = holder.takeNext(); - if (eventPkg == null) { - return; - } + let eventPkg = null; + while ((eventPkg = holder.takeNext()) != null) { console.info("eventPkg.packageId=" + eventPkg.packageId); console.info("eventPkg.row=" + eventPkg.row); console.info("eventPkg.size=" + eventPkg.size); @@ -324,15 +322,14 @@ let holder = hiAppEvent.addWatcher({ name: "watcher2", }); if (holder != null) { - let eventPkg = holder.takeNext(); - if (eventPkg == null) { - return; - } - console.info("eventPkg.packageId=" + eventPkg.packageId); - console.info("eventPkg.row=" + eventPkg.row); - console.info("eventPkg.size=" + eventPkg.size); - for (const eventInfo of eventPkg.data) { - console.info("eventPkg.data=" + eventInfo); + let eventPkg = null; + while ((eventPkg = holder.takeNext()) != null) { + console.info("eventPkg.packageId=" + eventPkg.packageId); + console.info("eventPkg.row=" + eventPkg.row); + console.info("eventPkg.size=" + eventPkg.size); + for (const eventInfo of eventPkg.data) { + console.info("eventPkg.data=" + eventInfo); + } } } ``` @@ -408,15 +405,36 @@ Defines a subscription data holder for processing subscription events. **System capability**: SystemCapability.HiviewDFX.HiAppEvent +### constructor9+ + +constructor(watcherName: string); + +A constructor used to create a **holder** object. It is called automatically when a **Watcher** object is added. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +``` + ### setSize9+ setSize(size: number): void Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); holder.setSize(1000); ``` @@ -426,9 +444,14 @@ takeNext(): [AppEventPackage](#appeventpackage9) Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); let eventPkg = holder.takeNext(); ``` diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 5620062988d8b16d374f7cfc010e2b77b378cb3a..53af9c42a3aa2d8cddf8d38290f7a29c30f8f9d6 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,6 +1,7 @@ # HiDebug -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. @@ -16,7 +17,7 @@ import hidebug from '@ohos.hidebug'; getNativeHeapSize(): bigint -Obtains the total size of the native heap memory. +Obtains the total size of the heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. @@ -26,7 +27,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. | Type | Description | | ------ | --------------------------- | -| bigint | Total size of the native heap memory, in kB.| +| bigint | Total size of the heap memory of this application, in kB.| **Example** @@ -39,7 +40,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. getNativeHeapAllocatedSize(): bigint -Obtains the size of the allocated native heap memory. +Obtains the size of the allocated heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. @@ -49,7 +50,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. **Return value** | Type | Description | | ------ | --------------------------------- | -| bigint | Size of the allocated native heap memory, in kB.| +| bigint | Size of the allocated heap memory of this application, in kB.| **Example** @@ -62,7 +63,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. getNativeHeapFreeSize(): bigint -Obtains the size of the free native heap memory. +Obtains the size of the free heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. @@ -72,7 +73,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. **Return value** | Type | Description | | ------ | ------------------------------- | -| bigint | Size of the free native heap memory, in kB.| +| bigint | Size of the free heap memory of this application, in kB.| **Example** @@ -85,7 +86,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. getPss(): bigint -Obtains the PSS of this process. +Obtains the size of the used physical memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -93,7 +94,7 @@ Obtains the PSS of this process. **Return value** | Type | Description | | ------ | ------------------------- | -| bigint | PSS of the process, in kB.| +| bigint | Used physical memory of this process, in kB.| **Example** @@ -114,7 +115,7 @@ Obtains the size of the shared dirty memory of this process. **Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the shared dirty memory of the process, in kB.| +| bigint | Size of the shared dirty memory of this process, in kB.| **Example** @@ -134,7 +135,7 @@ Obtains the size of the private dirty memory of this process. **Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the private dirty memory of the process, in kB.| +| bigint | Size of the private dirty memory of this process, in kB.| **Example** @@ -156,7 +157,7 @@ For example, if the CPU usage is **50%**, **0.5** is returned. **Return value** | Type | Description | | ------ | -------------------------- | -| number | CPU usage of the process.| +| number | CPU usage of this process.| **Example** @@ -220,7 +221,7 @@ Exports data from the specified heap file. | Name | Type | Mandatory | Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the app based on the specified `filename`.| +| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index e3c08ce24cf92eda9534812d664aa466c4b7c1ef..553ff5a9925a30f262acb49bb69cd4e95c7bd95b 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -2,7 +2,7 @@ Provides system event logging APIs for system HAP applications. -> **NOTE**
+> **NOTE** > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs. @@ -19,7 +19,7 @@ Enumerates event types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | FAULT | 1 | Error event.| | STATISTIC | 2 | Statistic event.| @@ -32,7 +32,7 @@ Defines a system event. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -50,7 +50,7 @@ Writes event information to the event file. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | | info | [SysEventInfo](#syseventinfo) | Yes| System event information.| | callback | AsyncCallback<void> | Yes| Callback used to process the received return value.
- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| @@ -60,20 +60,24 @@ Writes event information to the event file. This API uses an asynchronous callba ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}, (err, val) => { - // do something here. -}) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }, (err, val) => { + // do something here. + }) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` @@ -87,13 +91,13 @@ Writes event information to the event file. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory| Description| +| Name | Type | Mandatory | Description| | --------- | ----------------------- | ---- | --------------- | | info | [SysEventInfo](#syseventinfo) | Yes | System event information.| **Return value** -| Type | Description | +| Type | Description | | ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| @@ -102,26 +106,30 @@ Writes event information to the event file. This API uses a promise to return th ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}).then( - (val) => { - // do something here. - } -).catch( - (err) => { - // do something here. - } -) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }).then( + (val) => { + // do something here. + } + ).catch( + (err) => { + // do something here. + } + ) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` ## RuleType @@ -130,7 +138,7 @@ Enumerates matching rule types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | WHOLE_WORD | 1 | Whole word matching.| | PREFIX | 2 | Prefix matching.| @@ -142,7 +150,7 @@ Defines rules for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -155,7 +163,7 @@ Defines a watcher for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| | onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| @@ -173,36 +181,34 @@ Adds a watcher for event subscription. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| -**Return value** - -| Type | Description| -| ------- | -------------------------------------------------- | -| number | Event subscription result.
- **0**: Event subscription is successful.
- A value smaller than **0**: Event subscription has failed.| - **Example** ```js import hiSysEvent from '@ohos.hiSysEvent'; let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +try { + hiSysEvent.addWatcher(watcher) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); } -let ret = hiSysEvent.addWatcher(watcher) ``` ## hiSysEvent.removeWatcher @@ -217,37 +223,35 @@ Removes a watcher used for event subscription. **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory | Description | | ------ | ------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| -**Return value** - -| Type | Description| -| ------- | ----------------------------------------------------------- | -| number | Result of removing the watcher.
- **0**: Removing the watcher is successful.
- A value smaller than **0**: Removing the watcher has failed.| - **Example** ```js import hiSysEvent from '@ohos.hiSysEvent'; let watcher = { - rules: [{ - domain: "RELIABILITY", - name: "STACK", - tag: "STABILITY", - ruleType: hiSysEvent.RuleType.WHOLE_WORD, - }], - onEvent: (info) => { - // do something here. - }, - onServiceDied: () => { - // do something here. - } + rules: [{ + domain: "RELIABILITY", + name: "STACK", + tag: "STABILITY", + ruleType: hiSysEvent.RuleType.WHOLE_WORD, + }], + onEvent: (info) => { + // do something here. + }, + onServiceDied: () => { + // do something here. + } +} +try { + hiSysEvent.addWatcher(watcher) + hiSysEvent.removeWatcher(watcher) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); } -let ret = hiSysEvent.addWatcher(watcher) -hiSysEvent.removeWatcher(watcher) ``` ## QueryArg @@ -256,7 +260,7 @@ Defines arguments for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | beginTime | number | Yes| Start time (13-digit timestamp) for event query.| | endTime | number | Yes| End time (13-digit timestamp) for event query.| @@ -268,7 +272,7 @@ Defines rules for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | names | string[] | Yes| Array of event names.| @@ -279,9 +283,9 @@ Defines an event query instance. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[], seqs: number[]) => void| +| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| | onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| ## hiSysEvent.query @@ -296,50 +300,48 @@ Queries system events. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| | querier | [Querier](#querier) | Yes | Event query instance.| -**Return value** - -| Type | Description | -| ------- | ----------------------------------------------------------- | -| number | Event query result.
- **0**: Event query is successful.
- A value smaller than **0**: Event query has failed.| - **Example** ```js import hiSysEvent from '@ohos.hiSysEvent'; -hiSysEvent.write({ - domain: "RELIABILITY", - name: "STACK", - eventType: hiSysEvent.EventType.FAULT, - params: { - PID: 487, - UID: 103, - PACKAGE_NAME: "com.ohos.hisysevent.test", - PROCESS_NAME: "syseventservice", - MSG: "no msg." - } -}, (err, val) => { - // do something here. -}) -hiSysEvent.query({ - beginTime: -1, - endTime: -1, - maxEvents: 5, -}, [{ - domain: "RELIABILITY", - names: ["STACK"], -}], { - onQuery: function (infos, seqs) { - // do something here. - }, - onComplete: function(reason, total) { - // do something here. - } -}) +try { + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 487, + UID: 103, + PACKAGE_NAME: "com.ohos.hisysevent.test", + PROCESS_NAME: "syseventservice", + MSG: "no msg." + } + }, (err, val) => { + // do something here. + }) + hiSysEvent.query({ + beginTime: -1, + endTime: -1, + maxEvents: 5, + }, [{ + domain: "RELIABILITY", + names: ["STACK"], + }], { + onQuery: function (infos) { + // do something here. + }, + onComplete: function(reason, total) { + // do something here. + } + }) +} catch (error) { + console.error(`error code: ${error.code}, error msg: ${error.message}`); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md index cbaf898f75c37ba8921fe3d8ffd11e5484ec28e8..198615d8bf57c3749b527eb7fcc7fccdcaeb9fe1 100644 --- a/en/application-dev/reference/apis/js-apis-hitracechain.md +++ b/en/application-dev/reference/apis/js-apis-hitracechain.md @@ -71,7 +71,7 @@ Defines a **HiTraceId** object. ## hiTraceChain.begin -begin(name: string, flags: number = HiTraceFlag.DEFAULT): HiTraceId +begin(name: string, flags?: number): HiTraceId Starts call chain tracing. This API works in synchronous manner. @@ -82,7 +82,7 @@ Starts call chain tracing. This API works in synchronous manner. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | name | string | Yes| Traced service name. | -| flags | number | Yes| Trace flag combination. For details, see [HiTraceFlag](#hitraceflag). | +| flags | number | No| Trace flag combination. For details, see [HiTraceFlag](#hitraceflag). | **Return Value** @@ -113,7 +113,7 @@ Stops call chain tracing. This API works in synchronous manner. **Example** ```js -let asyncTraceId = hiTraceChain.begin("business"); +let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // End the call chain tracing after the service logic is executed for several times. hiTraceChain.end(asyncTraceId); ``` @@ -135,7 +135,7 @@ Obtains the trace ID. This API works in synchronous manner. **Example** ```js -let traceId = hiTraceChain.begin("business"); +let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // Obtain the current trace ID after the service logic is executed for several times. let curTraceId = hiTraceChain.getId(); ``` @@ -158,7 +158,7 @@ Sets a trace ID. This API works in synchronous manner. ```js let asyncTraceId; -let traceId = hiTraceChain.begin("business"); +let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // Set the current trace ID after the service logic is executed for several times. hiTraceChain.setId(asyncTraceId); ``` @@ -174,7 +174,7 @@ Clears the trace ID. This API works in synchronous manner. **Example** ```js -let traceId = hiTraceChain.begin("business"); +let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // Clear the current trace ID after the service logic is executed for several times. hiTraceChain.clearId(); ``` @@ -196,7 +196,7 @@ Creates a trace span. This API works in synchronous manner. **Example** ```js -let traceId = hiTraceChain.begin("business"); +let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); // Create a trace span after the service logic is executed for several times. let spanTraceId = hiTraceChain.createSpan(); ``` @@ -249,7 +249,7 @@ Checks whether a **HiTraceId** instance is valid. This API works in synchronous **Example** ```js -let traceId = hiTraceChain.begin("business"); +let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT); let traceIdIsvalid = hiTraceChain.isValid(traceId); ``` @@ -291,6 +291,7 @@ Enables the specified trace flag in the **HiTraceId** instance. This API works i **System capability**: SystemCapability.HiviewDFX.HiTrace **Parameters** + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | id | [HiTraceId](#hitraceid) | Yes | **HiTraceId** instance. | diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 9e0e0bf5160d01596d0c6e0969c3cc783712f45a..294ed0fa79032d4e47e6c9c999183811d272acd3 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -358,7 +358,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques | Name | Type | Mandatory| Description | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | method | [RequestMethod](#requestmethod) | No | Request method. | -| extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.8+
- To pass in a string object, you first need to encode the object on your own.8+ | +| extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.8+ | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | @@ -432,7 +432,7 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| +| result | string \| Object \| ArrayBuffer6+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 2d66bc9c61a54f3bfa88d6e7f27aa93fabd49a2d..a886b6c643be1295bd49f0bf166d1e244d82f9af 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -12,1218 +12,2277 @@ The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by app ```js import huks from '@ohos.security.huks' ``` -## HuksErrorCode -Enumerates the error codes. +## HuksParam -**System capability**: SystemCapability.Security.Huks +Defines the **param** in the **properties** array of **options** used in the APIs. -| Name | Value | Description| -| -------------------------- | ----- | ---- | -| HUKS_SUCCESS | 0 |Success.| -| HUKS_FAILURE | -1 |Failure.| -| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| -| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| -| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| -| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| -| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| -| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| -| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| -| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| -| HUKS_ERROR_STORAGE_FAILURE | -10 |Storage failure.| -| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| -| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| -| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| -| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| -| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| -| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| -| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| -| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| -| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| -| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| -| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| -| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| -| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| -| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| -| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| -| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| -| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| -| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| -| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| -| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| -| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| -| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| -| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| -| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| -| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| -| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| -| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| -| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| -| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| -| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| -| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| -| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| -| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| -| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to check whether the ALG is obtained. | -| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to check whether the key size is obtained.| -| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to check whether padding is obtained.| -| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to check whether the purpose is obtained.| -| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to check whether digest is obtained.| -| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to check whether the mode is obtained.| -| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to check whether the nonce is obtained.| -| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to check whether the AAD is obtained.| -| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to check whether the initialization vector (IV) is obtained.| -| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to check whether the AE flag is obtained.| -| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to check whether the SALT is obtained.| -| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to check whether the iteration is obtained.| -| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| -| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| -| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding.| -| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid purpose.| -| HUKS_ERROR_INVALID_MODE | -116 |Invalid mode.| -| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest.| -| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| -| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| -| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| -| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| -| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| -| HUKS_ERROR_INVALID_SALT | -123 |Invalid SALT.| -| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration.| -| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| -| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| -| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| -| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| -| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| +**System capability**: SystemCapability.Security.Huks +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------ | +| tag | [HuksTag](#hukstag) | Yes | Tag. | +| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| -## HuksKeyPurpose +## HuksOptions -Enumerates the key purposes. +Defines the **options** used in the APIs. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------ | ---- | -------------------------------- | -| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt plaintext.| -| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| -| HUKS_KEY_PURPOSE_SIGN | 4 | Used to sign data. | -| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signed data. | -| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | -| HUKS_KEY_PURPOSE_WRAP | 32 | Used to wrap a key. | -| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used to unwrap a key. | -| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | -| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------- | ---- | ------------------------ | +| properties | Array\<[HuksParam](#huksparam)> | No | Properties used to hold the **HuksParam** array.| +| inData | Uint8Array | No | Input data. | -## HuksKeyDigest +## HuksSessionHandle9+ -Enumerates the digest algorithms. +Defines the HUKS handle structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_DIGEST_NONE | 0 | No digest algorithm| -| HUKS_DIGEST_MD5 | 1 | MD5| -| HUKS_DIGEST_SM39+ | 2 | SM3| -| HUKS_DIGEST_SHA1 | 10 | SHA1| -| HUKS_DIGEST_SHA224 | 11 | SHA-224| -| HUKS_DIGEST_SHA256 | 12 | SHA-256| -| HUKS_DIGEST_SHA384 | 13 | SHA-384| -| HUKS_DIGEST_SHA512 | 14 | SHA-512| +| Name | Type | Mandatory| Description | +| --------- | ---------- | ---- | ---------------------------------------------------- | +| handle | number | Yes | Value of the handle. | +| challenge | Uint8Array | No | Challenge obtained after the [init](#huksinit) operation.| -## HuksKeyPadding +## HuksReturnResult9+ -Enumerates the padding algorithms. +Defines the **HuksResult** structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_PADDING_NONE | 0 | No padding algorithm| -| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| -| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| -| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5| -| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS) #5| -| HUKS_PADDING_PKCS7 | 5 | PKCS #7| -## HuksCipherMode -Enumerates the cipher modes. +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------- | ---- | ---------------- | +| outData | Uint8Array | No | Output data. | +| properties | Array\<[HuksParam](#huksparam)> | No | Property information. | +| certChains | Array\ | No | Certificate chain information.| -**System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------- | ---- | --------------------- | -| HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode| -| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| -| HUKS_MODE_CTR | 3 | Counter (CTR) mode| -| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| -| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| -| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| +## huks.generateKeyItem9+ -## HuksKeySize +generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key sizes. +Generates a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------- | ---- | ------------------------------------------ | -| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | -| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | -| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | -| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | -| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | -| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | -| HUKS_ECC_KEY_SIZE_224 | 224 | ECC key of 224 bits | -| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | -| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | -| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | -| HUKS_AES_KEY_SIZE_128 | 128 | AES key of 128 bits | -| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | -| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | -| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | -| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| -| HUKS_DH_KEY_SIZE_2048 | 2048 | DH key of 2048 bits | -| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | -| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | -| HUKS_SM2_KEY_SIZE_2569+ | 256 | SM2 key of 256 bits | -| HUKS_SM4_KEY_SIZE_1289+ | 128 | SM4 key of 128 bits | +**Parameters** -## HuksKeyAlg +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the key algorithms. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------- | ---- | --------------------- | -| HUKS_ALG_RSA | 1 | RSA | -| HUKS_ALG_ECC | 2 | ECC | -| HUKS_ALG_DSA | 3 | DSA | -| HUKS_ALG_AES | 20 | AES | -| HUKS_ALG_HMAC | 50 | HMAC | -| HUKS_ALG_HKDF | 51 | HKDF | -| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | -| HUKS_ALG_ECDH | 100 | ECDH | -| HUKS_ALG_X25519 | 101 | X25519 | -| HUKS_ALG_ED25519 | 102 | ED25519| -| HUKS_ALG_DH | 103 | DH | -| HUKS_ALG_SM29+ | 150 | SM2 | -| HUKS_ALG_SM39+ | 151 | SM3 | -| HUKS_ALG_SM49+ | 152 | SM4 | +## huks.generateKeyItem9+ -## HuksKeyGenerateType +generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the key generation types. +Generates a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------------ | ---- | ---------------- | -| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| -| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| -| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| +**Parameters** -## HuksKeyFlag +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| -Enumerates the key generation modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------------- | ---- | ------------------------------------ | -| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using an API. | -| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using an API. | -| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using a key agreement API.| -| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is derived by using an API.| +## huks.deleteKeyItem9+ -## HuksKeyStorageType +deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key storage modes. +Deletes a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ----------------------- | ---- | ------------------------------ | -| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | -| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| +**Parameters** -## HuksSendType +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the tag transfer modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: deleteKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------- | ---- | ----------------- | -| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| -| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| +## huks.deleteKeyItem9+ -## HuksUnwrapSuite9+ +deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the algorithm suites used when a wrapped key is imported. +Deletes a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------------------- | ---- | ----------------------------------------------------- | -| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| -| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | - -## HuksImportKeyType9+ +**Parameters** -Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| ------------------------- | ---- | ------------------------------ | -| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | -| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | -| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| - -## HuksUserAuthType9+ - -Enumerates the user authentication types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------- | -| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | -| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| -| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| - -## HuksAuthAccessType9+ - -Enumerates the access control types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| --------------------------------------- | ---- | ------------------------------------------------ | -| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key is invalid after the password is cleared. | -| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key is invalid after a new biometric feature is added.| - -## HuksChallengeType9+ - -Enumerates the types of the challenges generated when a key is used. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| -| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| -| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| - -## HuksChallengePosition9+ - -Enumerates the positions of the 8-byte valid value in a custom challenge generated. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31 indicate the valid challenge of the key.| - -## HuksSecureSignType9+ - -Defines the signature type of the key generated or imported. - -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: deleteKeyItem key success`); + }) + .catch(error => { + console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------------ | ---- | ------------------------------------------------------------ | -| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used to sign data, the data will be added with the authentication information and then be signed.| +## huks.getSdkVersion -## HuksTagType +getSdkVersion(options: HuksOptions) : string -Enumerates the tag data types. +Obtains the SDK version of the current system. **System capability**: SystemCapability.Security.Huks +**Parameters** -| Name | Value | Description | -| --------------------- | ------- | --------------------------------------- | -| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | -| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | -| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| -| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | -| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | -| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | +| Name | Type | Mandatory| Description | +| ------- | ---------- | ---- | ------------------------- | +| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| -## HuksTag +**Return value** -Enumerates the tags used to invoke parameters. +| Type | Description | +| ------ | ------------- | +| string | SDK version obtained.| -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | -| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | -| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | -| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | -| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | -| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | -| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | -| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | -| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | -| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | -| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | -| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | -| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | -| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | -| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | -| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | -| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | -| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | -| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | -| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | -| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | -| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | -| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | -| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | -| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | -| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite used when a wrapped key is imported. | -| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | -| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | -| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | -| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | -| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | -| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | -| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | -| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set the authentication type to **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, or their combination.| -| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | -| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | -| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| -| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| -| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| -| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| -| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | -| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | -| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. | -| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | -| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. | -| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. | -| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. | -| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Device manufacturer. | -| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | -| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. | -| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | -| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | -| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| -| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | -| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | -| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | -| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | -| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | -| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | -| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | -| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | -| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | -| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | -| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | -| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | -| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | -| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | -| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | -| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | -| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | -| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | -| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | -| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | -| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | -| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | -| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | +```js +/* Set options to emptyOptions. */ +let emptyOptions = { + properties: [] +}; +let result = huks.getSdkVersion(emptyOptions); +``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Generates a key. This API uses an asynchronous callback to return the result. +Imports a key in plaintext. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code defined in **HuksResult** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Generate an RSA key of 512 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_OAEP + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var options = { - properties: properties +let options = { + properties: properties, + inData: plainTextSize32 }; -huks.generateKey(keyAlias, options, function (err, data){}); +try { + huks.importKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: importKeyItem success`); + } + }); +} catch (error) { + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions) : Promise\ +importKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Generates a key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| - -**Return value** - -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Example** ```js -/* Generate an ECC key of 256 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; -var options = { - properties: properties +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var result = huks.generateKey(keyAlias, options); +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +try { + huks.importKeyItem(keyAlias, huksoptions) + .then ((data) => { + console.info(`promise: importKeyItem success`); + }) + .catch(error => { + console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Deletes a key. This API uses an asynchronous callback to return the result. +Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated. | -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + huks.attestKeyItem(aliasString, options, function (error, data) { + if (error) { + console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: attestKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions) : Promise\ +attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Deletes a key. This API uses a promise to return the result. +Obtains the certificate used to verify a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ----------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated.| -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | --------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -var result = huks.deleteKey(keyAlias, emptyOptions); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + await huks.generateKeyItem(alias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + await huks.attestKeyItem(aliasString, options) + .then ((data) => { + console.info(`promise: attestKeyItem success`); + }) + .catch(error => { + console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.getSdkVersion +## huks.importWrappedKeyItem9+ -getSdkVersion(options: HuksOptions) : string +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the SDK version of the current system. +Imports a wrapped key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------- | ---- | ------------------------- | -| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| - -**Return value** - -| Type | Description | -| ------ | ------------- | -| string | SDK version obtained.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var emptyOptions = { - properties: [] +import huks from '@ohos.security.huks'; + +let exportWrappingKey; +let alias1 = "importAlias"; +let alias2 = "wrappingKeyAlias"; + +async function TestGenFunc(alias, options) { + try { + await genKey(alias, options) + .then((data) => { + console.info(`callback: generateKeyItem success`); + }) + .catch(error => { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function genKey(alias, options) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestExportFunc(alias, options) { + try { + await exportKey(alias, options) + .then ((data) => { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportWrappingKey = data.outData; + }) + .catch(error => { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function exportKey(alias, options) : Promise { + return new Promise((resolve, reject) => { + try { + huks.exportKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await importWrappedKey(alias, wrappingAlias, options) + .then ((data) => { + console.info(`callback: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function importWrappedKey(alias, wrappingAlias, options) { + return new Promise((resolve, reject) => { + try { + huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedKeyFunc( + alias, + wrappingAlias, + genOptions, + importOptions +) { + await TestGenFunc(wrappingAlias, genOptions); + await TestExportFunc(wrappingAlias, genOptions); + + /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. + * For example, import **keyA**. + * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. + * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. + * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. + * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**. + * 5. Generate the **importOptions.inData** field in the following format: + * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + + * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + + * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + + * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + + * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc + */ + let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); + importOptions.inData = inputKey; + await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +} + +function makeGenerateOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, + value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, + }; + let options = { + properties: properties + }; + return options; }; -var result = huks.getSdkVersion(emptyOptions); + +function makeImportOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, + value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING + }; + let options = { + properties: properties + }; + return options; +}; + +function huksImportWrappedKey() { + let genOptions = makeGenerateOptions(); + let importOptions = makeImportOptions(); + TestImportWrappedKeyFunc( + alias1, + alias2, + genOptions, + importOptions + ); +} ``` -## huks.importKey +## huks.importWrappedKeyItem9+ -importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses an asynchronous callback to return the result. +Imports a wrapped key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| **Example** ```js -/* Import an AES key of 256 bits. */ -var plainTextSize32 = makeRandomArr(32); -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); +/* The process is similar as if a callback is used, except the following:*/ +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await huks.importWrappedKeyItem(alias, wrappingAlias, options) + .then ((data) => { + console.info(`promise: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } - return arr; -}; -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var options = { - properties: properties, - inData: plainTextSize32 +} +``` + +## huks.exportKeyItem9+ + +exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Exports a key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -huks.importKey(keyAlias, options, function (err, data){}); +try { + huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.importKey +## huks.exportKeyItem9+ -importKey(keyAlias: string, options: HuksOptions) : Promise\ +exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses a promise to return the result. +Exports a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | ------------------------------------------------------------ | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js -/* Import an AES key of 128 bits. */ -var plainTextSize32 = makeRandomArr(32); - -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); - } - return arr; -}; - -/* Step 1 Generate a key. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var huksoptions = { - properties: properties, - inData: plainTextSize32 +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -var result = huks.importKey(keyAlias, huksoptions); +try { + huks.exportKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.attestkey9+ +## huks.getKeyItemProperties9+ -attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. +Obtains key properties. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.getKeyItemProperties9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\ - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; +Obtains key properties. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options, function (err, data) { - printLog(`key attest result : ${JSON.stringify(data)}`); - }); +## huks.isKeyItemExist9+ + +isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Checks whether a key exists. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------- | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`); + } else { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } ``` -## huks.attestkey9+ +## huks.isKeyItemExist9+ -attestKey(keyAlias: string, options: HuksOptions) : Promise\ +isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\ -Obtains the certificate used to verify a key. This API uses a promise to return the result. +Checks whether a key exists. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.initSession9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; -} +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options) - .then((data) => { - console.log(`test attestKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test attestKey information: ' + JSON.stringify(err)); - }); -} -``` +**System capability**: SystemCapability.Security.Huks -## huks.importWrappedKey9+ +**Parameters** -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | +| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes | Callback invoked to return the key operation handle.| -Imports a wrapped key. This API uses an asynchronous callback to return the result. + +## huks.initSession9+ + +initSession(keyAlias: string, options: HuksOptions) : Promise\ + +Initializes the data for a key operation. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | Yes | Token of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Updates the key operation data by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ----------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | No | Token for the **Finish** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + + +## huks.abortSession9+ + +abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Aborts the use of the key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** ```js -var exportWrappingKey; -var alias1 = "importAlias"; -var alias2 = "wrappingKeyAlias"; - -async function TestGenFunc(alias, options) { - await genKey(alias, options) - .then((data) => { - console.log(`test genKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test genKey err information: ' + JSON.stringify(err)); - }); +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function genKey(alias, options) { - return new Promise((resolve, reject) => { - huks.generateKey(alias, options, function (err, data) { - console.log(`test genKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test genKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) +}; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } + + try { + await huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestExportFunc(alias, options) { - await exportKey(alias, options) - .then((data) => { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test exportKey err information: ' + JSON.stringify(err)); - }); +async function huksInit() { + console.log('enter huksInit'); + try { + huks.initSession(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + } + }); + } catch (error) { + console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function exportKey(alias, options) { - return new Promise((resolve, reject) => { - huks.exportKey(alias, options, function (err, data) { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test exportKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - exportWrappingKey = data.outData; - resolve(data); - } - }); - }); +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + huks.updateSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - await importWrappedKey(alias, wrappingAlias, options) - .then((data) => { - console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test importWrappedKey err information: ' + JSON.stringify(err)); - }); +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + huks.finishSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function importWrappedKey(alias, wrappingAlias, options) { - return new Promise((resolve, reject) => { - huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) { - console.log(`importWrappedKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('importWrappedKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +async function huksAbort() { + console.log('enter huksAbort'); + try { + huks.abortSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: abortSession success`); + } + }); + } catch (error) { + console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } +``` -async function TestImportWrappedKeyFunc( - alias, - wrappingAlias, - genOptions, - importOptions -) { - await TestGenFunc(wrappingAlias, genOptions); - await TestExportFunc(wrappingAlias, genOptions); +## huks.abortSession9+ - /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. - * For example, import **keyA**. - * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. - * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. - * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. - * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, ** aad2**, ciphertext **kek_enc**, and encrypted **tag2**. - * 5. Generate the **importOptions.inData** field in the following format: - * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + - * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + - * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + - * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + - * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc - */ - var inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); - importOptions.inData = inputKey; - await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +abortSession(handle: number, options: HuksOptions) : Promise\; + +Aborts the use of the key. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function makeGenerateOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - var options = { - properties: properties - }; - return options; +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) }; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } -function makeImportOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, - value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING - }; - var options = { - properties: properties - }; - return options; + try { + await huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksInit() { + console.log('enter huksInit'); + try { + await huks.initSession(keyAlias, options) + .then ((data) => { + console.info(`promise: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + }) + .catch(error => { + console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + await huks.updateSession(handle, options) + .then ((data) => { + console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + await huks.finishSession(handle, options) + .then ((data) => { + console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksAbort() { + console.log('enter huksAbort'); + try { + await huks.abortSession(keyAlias, options) + .then ((data) => { + console.info(`promise: abortSession success`); + }) + .catch(error => { + console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} +``` + + +## HuksExceptionErrCode9+ + +Enumerates the error codes. + +For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md). + +**System capability**: SystemCapability.Security.Huks + +| Name | Description | Error Code | +| ---------------------------------------------- | --------------------------- | -------- | +| HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | 201 | +| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | 401 | +| HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | 801 | +| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | 12000001 | +| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | 12000002 | +| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | 12000003 | +| HUKS_ERR_CODE_FILE_OPERATION_FAIL | The file operation failed. | 12000004 | +| HUKS_ERR_CODE_COMMUNICATION_FAIL | The communication failed. | 12000005 | +| HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | 12000006 | +| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 | +| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| 12000008 | +| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| 12000009 | +| HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | 12000010 | +| HUKS_ERR_CODE_ITEM_NOT_EXIST | The target object does not exist. | 12000011 | +| HUKS_ERR_CODE_EXTERNAL_ERROR | An external error occurs. | 12000012 | +| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The credential does not exist. | 12000013 | +| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | The memory is insufficient. | 12000014 | +| HUKS_ERR_CODE_CALL_SERVICE_FAILED | Failed to call other system services. | 12000015 | + +## HuksKeyPurpose + +Enumerates the key purposes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------- | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| +| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing. | +| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature. | +| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | +| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export. | +| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import. | +| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | +| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | + +## HuksKeyDigest + +Enumerates the digest algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_DIGEST_NONE | 0 | No digest algorithm| +| HUKS_DIGEST_MD5 | 1 | MD5| +| HUKS_DIGEST_SM39+ | 2 | SM3| +| HUKS_DIGEST_SHA1 | 10 | SHA-1| +| HUKS_DIGEST_SHA224 | 11 | SHA-224| +| HUKS_DIGEST_SHA256 | 12 | SHA-256| +| HUKS_DIGEST_SHA384 | 13 | SHA-384| +| HUKS_DIGEST_SHA512 | 14 | SHA-512| + +## HuksKeyPadding + +Enumerates the padding algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_PADDING_NONE | 0 | No padding algorithm| +| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| +| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| +| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5| +| HUKS_PADDING_PKCS5 | 4 | PKCS #5| +| HUKS_PADDING_PKCS7 | 5 | PKCS #7| + +## HuksCipherMode + +Enumerates the cipher modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------- | ---- | --------------------- | +| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode| +| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| +| HUKS_MODE_CTR | 3 | Counter (CTR) mode| +| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| +| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| +| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| + +## HuksKeySize + +Enumerates the key sizes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------- | ---- | ------------------------------------------ | +| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | +| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | +| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | +| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | +| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | +| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | +| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits | +| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | +| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | +| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | +| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | +| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | +| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | +| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | +| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| +| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits | +| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | +| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | +| HUKS_SM2_KEY_SIZE_2569+ | 256 | ShangMi2 (SM2) key of 256 bits | +| HUKS_SM4_KEY_SIZE_1289+ | 128 | ShangMi4 (SM4) key of 128 bits | + +## HuksKeyAlg + +Enumerates the key algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | --------------------- | +| HUKS_ALG_RSA | 1 | RSA | +| HUKS_ALG_ECC | 2 | ECC | +| HUKS_ALG_DSA | 3 | DSA | +| HUKS_ALG_AES | 20 | AES | +| HUKS_ALG_HMAC | 50 | HMAC | +| HUKS_ALG_HKDF | 51 | HKDF | +| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | +| HUKS_ALG_ECDH | 100 | ECDH | +| HUKS_ALG_X25519 | 101 | X25519 | +| HUKS_ALG_ED25519 | 102 | ED25519| +| HUKS_ALG_DH | 103 | DH | +| HUKS_ALG_SM29+ | 150 | SM2 | +| HUKS_ALG_SM39+ | 151 | SM3 | +| HUKS_ALG_SM49+ | 152 | SM4 | + +## HuksKeyGenerateType + +Enumerates the key generation types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------- | +| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| +| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| +| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| + +## HuksKeyFlag + +Enumerates the key generation modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------- | ---- | ------------------------------------ | +| HUKS_KEY_FLAG_IMPORT_KEY | 1 | Import a key using an API. | +| HUKS_KEY_FLAG_GENERATE_KEY | 2 | Generate a key by using an API. | +| HUKS_KEY_FLAG_AGREE_KEY | 3 | Generate a key by using a key agreement API.| +| HUKS_KEY_FLAG_DERIVE_KEY | 4 | Derive a key by using an API.| + +## HuksKeyStorageType + +Enumerates the key storage modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ----------------------- | ---- | ------------------------------ | +| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | +| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| + +## HuksSendType + +Enumerates the tag transfer modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------- | ---- | ----------------- | +| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| +| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| + +## HuksUnwrapSuite9+ + +Enumerates the algorithm suites required for encrypted imports. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------------------- | ---- | ----------------------------------------------------- | +| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| +| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | + +## HuksImportKeyType9+ + +Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------ | +| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | +| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | +| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| + +## HuksUserAuthType9+ + +Enumerates the user authentication types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------- | +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | +| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| +| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| + +## HuksAuthAccessType9+ + +Enumerates the access control types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------------------------- | ---- | ------------------------------------------------ | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key becomes invalid after the password is cleared. | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key becomes invalid after a new biometric feature is added.| + +## HuksChallengeType9+ + +Enumerates the types of the challenges generated when a key is used. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| +| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| +| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| + +## HuksChallengePosition9+ + +Enumerates the positions of the 8-byte valid value in a custom challenge generated. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7.| +| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15.| +| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23.| +| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31.| + +## HuksSecureSignType9+ + +Defines the signature type of the key generated or imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ------------------------------------------------------------ | +| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.| + +## HuksTagType + +Enumerates the tag data types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | +| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | +| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| +| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | +| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | +| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | + +## HuksTag + +Enumerates the tags used to invoke parameters. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | +| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | +| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. | +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | +| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | +| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports. | +| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | +| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | +| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | +| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | +| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | +| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | +| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT | +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | +| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| +| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| +| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| +| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | +| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device. | +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device. | +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device. | +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device. | +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device. | +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | +| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | +| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | +| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | +| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | +| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | +| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | +| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | +| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | +| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | +| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | +| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | +| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | +| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | +| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | +| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | +| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | +| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | +| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | +| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | +| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | +| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Generates a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. For details about other results, see HuksResult.| + +**Example** + +```js +/* Generate an RSA key of 512 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_OAEP +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +huks.generateKey(keyAlias, options, function (err, data){}); +``` + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions) : Promise\ + +Generates a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +let result = huks.generateKey(keyAlias, options); +``` + + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Deletes a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +``` + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions) : Promise\ + +Deletes a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +let result = huks.deleteKey(keyAlias, emptyOptions); +``` + + +## huks.importKey(deprecated) + +importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Imports a key in plaintext. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------------------------------- | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; - -function huksImportWrappedKey() { - var genOptions = makeGenerateOptions(); - var importOptions = makeImportOptions(); - TestImportWrappedKeyFunc( - alias1, - alias2, - genOptions, - importOptions - ); -} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let options = { + properties: properties, + inData: plainTextSize32 +}; +huks.importKey(keyAlias, options, function (err, data){}); ``` -## huks.importWrappedKey9+ +## huks.importKey(deprecated) -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ +importKey(keyAlias: string, options: HuksOptions) : Promise\ -Imports a wrapped key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9-1). **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------------- | ---- | --------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Return value** | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* The process is similar as if a callback is used, except the following:*/ -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - var result = await huks.importWrappedKey(alias, wrappingAlias, options); - if (result.errorCode === 0) { - console.log('test importWrappedKey success'); - } else { - console.log('test importWrappedKey fail'); - } -} +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +let result = huks.importKey(keyAlias, huksoptions); ``` -## huks.exportKey + +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Exports a key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1232,25 +2291,27 @@ Exports a key. This API uses an asynchronous callback to return the result. | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.exportKey(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.exportKey +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions) : Promise\ Exports a key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1264,25 +2325,28 @@ Exports a key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.exportKey(keyAlias, emptyOptions); +let result = huks.exportKey(keyAlias, emptyOptions); ``` -## huks.getKeyProperties + +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Obtains key properties. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1291,25 +2355,27 @@ Obtains key properties. This API uses an asynchronous callback to return the res | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.getKeyProperties +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ Obtains key properties. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1323,25 +2389,28 @@ Obtains key properties. This API uses a promise to return the result. | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned. **properties** returns the parameters required for generating the key.| +| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.getKeyProperties(keyAlias, emptyOptions); +let result = huks.getKeyProperties(keyAlias, emptyOptions); ``` -## huks.isKeyExist + +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Checks whether a key exists. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1350,25 +2419,27 @@ Checks whether a key exists. This API uses an asynchronous callback to return th | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the key to check.| | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| -| callback | AsyncCallback\ | Yes | Callback used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.isKeyExist +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ Checks whether a key exists. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1382,26 +2453,26 @@ Checks whether a key exists. This API uses a promise to return the result. | Type | Description | | ----------------- | --------------------------------------- | -| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.isKeyExist(keyAlias, emptyOptions); +let result = huks.isKeyExist(keyAlias, emptyOptions); ``` - - -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Initializes the data for a key operation. This API uses an asynchronous callback to return the result. +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1411,14 +2482,16 @@ Initializes the data for a key operation. This API uses an asynchronous callback | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the initialization operation.| +| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback invoked to return the key operation handle.| -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions) : Promise\ -Initializes the data for a key operation. This API uses a promise to return the result. +Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1428,52 +2501,21 @@ Initializes the data for a key operation. This API uses a promise to return the | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the initialization operation.| - - -## huks.update(deprecated) - -update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void - -Updates the key operation data by segment. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.update9+](#huksupdate9-1). - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.| -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| ## huks.update(deprecated) -update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ - -Updates the key operation data by segment. This API uses a promise to return the result. - -> **NOTE**
This API is discarded since API version 9. You are advised to use [huks.update9+](#huksupdate9-2). - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - -## huks.update9+ - update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9). **System capability**: SystemCapability.Security.Huks @@ -1483,14 +2525,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| +## huks.update(deprecated) -## huks.update9+ +update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void -update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-1). **System capability**: SystemCapability.Security.Huks @@ -1499,15 +2542,17 @@ Updates the key operation by segment. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| token | Uint8Array | Yes | Token of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| -## huks.update9+ +## huks.update(deprecated) update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ -Updates the key operation by segment. This API uses a promise to return the result. +Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-2). **System capability**: SystemCapability.Security.Huks @@ -1516,15 +2561,23 @@ Updates the key operation by segment. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ----------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | token | Uint8Array | No | Token of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -## huks.finish +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| + + +## huks.finish(deprecated) finish(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9). **System capability**: SystemCapability.Security.Huks @@ -1534,14 +2587,16 @@ Completes the key operation and releases resources. This API uses an asynchronou | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| -## huks.finish +## huks.finish(deprecated) finish(handle: number, options: HuksOptions) : Promise\ -Completes the key operation and releases resources. This API uses a promise to return the result. +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1551,49 +2606,22 @@ Completes the key operation and releases resources. This API uses a promise to r | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void - -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | Yes | Token for the **Finish** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - - -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ - -Completes the key operation and releases resources. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | ----------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | No | Token for the **Finish** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions, callback: AsyncCallback\) : void Aborts the use of the key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1602,7 +2630,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| **Example** @@ -1612,27 +2640,14 @@ Aborts the use of the key. This API uses an asynchronous callback to return the * * The following uses the callback of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; async function generateKey() { properties[0] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, @@ -1657,11 +2672,11 @@ async function generateKey() { huks.generateKey(keyalias, options); } function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } async function huksInit() { @@ -1708,112 +2723,16 @@ async function huksAbort() { }); console.log(resultMessage); } - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('Tocallback') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - routePage() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions) : Promise\; Aborts the use of the key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1822,7 +2741,12 @@ Aborts the use of the key. This API uses a promise to return the result. | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| **Example** @@ -1832,34 +2756,20 @@ Aborts the use of the key. This API uses a promise to return the result. * * The following uses the promise of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} - -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } @@ -1890,7 +2800,7 @@ async function huksInit() { return new Promise((resolve, reject) => { huks.init(keyalias, options, async function (err, data) { if (data.errorCode === 0) { - resultMessage = "Initialization successful!" + resultMessage = "init success!" handle = data.handle; } else { resultMessage = "init fail errorCode: " + data.errorCode @@ -1935,128 +2845,10 @@ function huksAbort() { }); }); } -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('to Promise') - .fontSize(20) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - router.back() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## HuksParam - -Defines the **param** in the **properties** array of **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------------- | ---- | ------------ | -| tag | [HuksTag](#hukstag) | Yes | Tag. | -| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| - -## HuksOptions - -Defines the **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name | Type | Mandatory| Description | -| ---------- | ----------------- | ---- | ------------------------ | -| properties | Array\<[HuksParam](#huksparam)> | No | Array used to hold **HuksParam**.| -| inData | Uint8Array | No | Input data. | -## HuksHandle +## HuksHandle(deprecated) Defines the HUKS handle structure. @@ -2069,7 +2861,7 @@ Defines the HUKS handle structure. | token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| -## HuksResult +## HuksResult(deprecated) Defines the **HuksResult** structure. @@ -2083,3 +2875,87 @@ Defines the **HuksResult** structure. | outData | Uint8Array | No | Output data. | | properties | Array\<[HuksParam](#huksparam)> | No | Property information. | | certChains | Array\ | No | Certificate chain information.| + + +## HuksErrorCode(deprecated) + +Enumerates the error codes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description| +| -------------------------- | ----- | ---- | +| HUKS_SUCCESS | 0 |Success.| +| HUKS_FAILURE | -1 |Failure.| +| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| +| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| +| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| +| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| +| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| +| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| +| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| +| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| +| HUKS_ERROR_STORAGE_FAILURE | -10 |Insufficient storage space.| +| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| +| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| +| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| +| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| +| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| +| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| +| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| +| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| +| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| +| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| +| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| +| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| +| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| +| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| +| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| +| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| +| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| +| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| +| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| +| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| +| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| +| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| +| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| +| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| +| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| +| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| +| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| +| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| +| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| +| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| +| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| +| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| +| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| +| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. | +| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.| +| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.| +| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to obtain the key purpose.| +| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to obtain the digest algorithm.| +| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to obtain the cipher mode.| +| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to obtain the nonce.| +| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to obtain the AAD.| +| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to obtain the initialization vector (IV).| +| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to obtain the AE flag.| +| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to obtain the salt value.| +| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to obtain the number of iterations.| +| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| +| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| +| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding algorithm.| +| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid key purpose.| +| HUKS_ERROR_INVALID_MODE | -116 |Invalid cipher mode.| +| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest algorithm.| +| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| +| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| +| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| +| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| +| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| +| HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.| +| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.| +| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| +| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| +| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| +| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| +| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 866a5833b69feb01da451f2464fbdd7915f06172..6b7463a11b96f468bd275b0fd0fd841fe690713c 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -40,9 +40,11 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper const color = new ArrayBuffer(96); let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts) - .then((pixelmap) => { - }) +image.createPixelMap(color, opts).then((pixelmap) => { + console.log('Succeeded in creating pixelmap.'); +}).catch(error => { + console.log('Failed to create pixelmap.'); +}) ``` ## image.createPixelMap8+ @@ -115,7 +117,7 @@ const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer).then(() => { console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. }).catch(error => { - console.log('Failed to read image pixel data.'); // Called if no condition is met. + console.log('Failed to read image pixel data.'); // Called if no condition is met. }) ``` @@ -392,7 +394,6 @@ Obtains pixel map information of this image. This API uses a promise to return t const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } image.createPixelMap(color, opts).then(pixelmap => { - globalpixelmap = pixelmap; if (pixelmap == undefined) { console.error("Failed to obtain the image pixel map information."); } @@ -428,7 +429,6 @@ const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (err, pixelmap) => { if (pixelmap == undefined) { - globalpixelmap = pixelmap; console.error("Failed to obtain the image pixel map information."); } pixelmap.getImageInfo((err, imageInfo) => { @@ -559,9 +559,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return **Example** ```js -async function () { - var rate = 0.5; - await pixelmap.opacity(rate); +async function Demo() { + await pixelmap.opacity(0.5); } ``` @@ -582,9 +581,9 @@ Creates a **PixelMap** object that contains only the alpha channel information. **Example** ```js -async function () { - await pixelmap.createAlphaPixelmap(); -}) +async function Demo() { + await pixelmap.createAlphaPixelmap(); +} ``` ### createAlphaPixelmap9+ @@ -632,7 +631,7 @@ Scales this image based on the input width and height. This API uses an asynchro **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -661,7 +660,7 @@ Scales this image based on the input width and height. This API uses a promise t **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -685,7 +684,7 @@ Translates this image based on the input coordinates. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -714,7 +713,7 @@ Translates this image based on the input coordinates. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -737,7 +736,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -765,7 +764,7 @@ Rotates this image based on the input angle. This API uses a promise to return t **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -789,7 +788,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -818,7 +817,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -841,7 +840,7 @@ Crops this image based on the input size. This API uses an asynchronous callback **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -869,7 +868,7 @@ Crops this image based on the input size. This API uses a promise to return the **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -891,15 +890,10 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }).catch(error => { - console.log('Failed to release pixelmap object.'); - }) +pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); +}).catch(error => { + console.log('Failed to release pixelmap object.'); }) ``` @@ -920,13 +914,8 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }) +pixelmap.release(() => { + console.log('Succeeded in releasing pixelmap object.'); }) ``` @@ -1345,11 +1334,10 @@ Modifies the value of a property in this image. This API uses a promise to retur **Example** ```js -imageSourceApi.modifyImageProperty("ImageWidth", "120") - .then(() => { - const w = imageSourceApi.getImageProperty("ImageWidth") - console.info('w', w); - }) +imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => { + const w = imageSourceApi.getImageProperty("ImageWidth") + console.info('w', w); +}) ``` ### modifyImageProperty9+ @@ -1401,9 +1389,9 @@ Updates incremental data. This API uses a promise to return the result. ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => { - console.info('Succeeded in updating data.'); - }) +imageSourceApi.updateData(array, false, 0, 10).then(data => { + console.info('Succeeded in updating data.'); +}) ``` @@ -1429,11 +1417,11 @@ Updates incremental data. This API uses an asynchronous callback to return the r ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> { - if(data !== undefined){ - console.info('Succeeded in updating data.'); - } - }) +imageSourceApi.updateData(array, false, 0, 10,(error,data )=> { + if(data !== undefined){ + console.info('Succeeded in updating data.'); + } +}) ``` ### createPixelMap7+ @@ -1617,6 +1605,7 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` @@ -1645,6 +1634,7 @@ Packs an image. This API uses a promise to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 } imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { @@ -1673,10 +1663,14 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts, data => { - console.log('Succeeded in packing the image.'); +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts, data => { + console.log('Succeeded in packing the image.'); + }) }) ``` @@ -1704,14 +1698,18 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts) - .then( data => { - console.log('Succeeded in packing the image.'); - }).catch(error => { - console.log('Failed to pack the image..'); - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts) + .then( data => { + console.log('Succeeded in packing the image.'); + }).catch(error => { + console.log('Failed to pack the image..'); + }) +}) ``` ### release @@ -1764,7 +1762,7 @@ imagePackerApi.release().then(()=>{ createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver -Create an **ImageReceiver** instance by specifying the image width, height, format, and capacity. +Creates an **ImageReceiver** instance by specifying the image width, height, format, and capacity. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver @@ -1774,7 +1772,7 @@ Create an **ImageReceiver** instance by specifying the image width, height, form | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format. | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1955,7 +1953,7 @@ receiver.readNextImage().then(img => { }) ``` -### on('imageArrival')9+ +### on9+ on(type: 'imageArrival', callback: AsyncCallback\): void @@ -2020,6 +2018,228 @@ receiver.release().then(() => { }) ``` +## image.createImageCreator9+ + +createImageCreator(width: number, height: number, format: number, capacity: number): ImageCreator + +Creates an **ImageCreator** instance by specifying the image width, height, format, and capacity. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| width | number | Yes | Default image width. | +| height | number | Yes | Default image height. | +| format | number | Yes | Image format, for example, YCBCR_422_SP or JPEG. | +| capacity | number | Yes | Maximum number of images that can be accessed at the same time.| + +**Return value** + +| Type | Description | +| ------------------------------ | --------------------------------------- | +| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| + +**Example** + +```js +var creator = image.createImageCreator(8192, 8, 4, 8); +``` + +## ImageCreator9+ + +Requests an image native data area, and provides APIs for applications to compile native image data. +Before calling any APIs in **ImageCreator**, you must create an **ImageCreator** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +| Name | Type | Readable| Writable| Description | +| -------- | ---------------------------- | ---- | ---- | ------------------ | +| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.| +| format | [ImageFormat](#imageformat9) | Yes | No | Image format. | + +### dequeueImage9+ + +dequeueImage(callback: AsyncCallback\): void + +Obtains an image buffer from the idle queue and writes image data into it. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage((err, img) => { + if (err) { + console.info('dequeueImage succeeded.'); + } + console.info('dequeueImage failed.')); +}); +``` + +### dequeueImage9+ + +dequeueImage(): Promise\ + +Obtains an image buffer from the idle queue and writes image data into it. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| --------------- | ------------- | +| Promise\ | Promise used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage().then(img => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.log('dequeueImage failed: ' + error); +}) +``` + +### queueImage9+ + +queueImage(interface: Image, callback: AsyncCallback\): void + +Places the drawn image in the dirty queue. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| interface | Image | Yes | Drawn image.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img, (err) => { + if (err) { + console.info('dequeueImage failed: ' + err); + } + console.info('dequeueImage succeeded'); +}) +``` + +### queueImage9+ + +queueImage(interface: Image): Promise\ + +Places the drawn image in the dirty queue. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------| ---- | ------------------- | +| interface | Image | Yes | Drawn image.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img).then(() => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.info('dequeueImage failed: ' + error); +}) +``` + +### on9+ + +on(type: 'imageRelease', callback: AsyncCallback\): void + +Listens for image release events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| type | string | Yes | Type of event, which is **'imageRelease'**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.on('imageRelease', (err) => { + if (err) { + console.info('on faild' + err); + } + console.info('on succeeded'); +}) +``` + +### release9+ + +release(callback: AsyncCallback\): void + +Releases this **ImageCreator** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release((err) => { + if (err) { + console.info('release failed: ' + err); + } + console.info('release succeeded'); +}); +``` +### release9+ + +release(): Promise\ + +Releases this **ImageCreator** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release().then(() => { + console.info('release succeeded'); +}).catch(error => { + console.info('release failed'); +}) +``` + ## Image9+ Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An **Image** instance is returned when [readNextImage](#readnextimage9) and [readLatestImage](#readlatestimage9) are called. @@ -2147,7 +2367,7 @@ Describes area information in an image. | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | pixels | ArrayBuffer | Yes | No | Pixels of the image. | | offset | number | Yes | No | Offset for data reading. | -| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | +| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| ## ImageInfo @@ -2159,6 +2379,7 @@ Describes image information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ---------- | | size | [Size](#size) | Yes | Yes | Image size.| +| density9+ | number | Yes | Yes | Pixel density, in ppi.| ## Size @@ -2181,8 +2402,13 @@ Enumerates the pixel formats of images. | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | -| RGBA_8888 | 3 | RGBA_8888. | -| BGRA_88889+ | 4 | BGRA_8888. | +| RGBA_8888 | 3 | RGBA_8888.| +| BGRA_88889+ | 4 | BGRA_8888.| +| RGB_8889+ | 5 | RGB_888. | +| ALPHA_89+ | 6 | ALPHA_8. | +| RGBA_F169+ | 7 | RGBA_F16. | +| NV219+ | 8 | NV21. | +| NV129+ | 9 | NV12. | ## AlphaType9+ @@ -2194,8 +2420,8 @@ Enumerates the alpha types of images. | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | +| PREMUL | 2 | Premultiplied alpha. | +| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | ## ScaleMode9+ @@ -2250,6 +2476,7 @@ Defines image decoding options. | desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| | index | number | Yes | Yes | Index of the image to decode. | +| fitDensity9+ | number | Yes | Yes | Image pixel density, in ppi. | ## Region7+ @@ -2260,7 +2487,7 @@ Describes region information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ------------ | | size | [Size](#size) | Yes | Yes | Region size. | -| x | number | Yes | Yes | X coordinate of the region.| +| x | number | Yes | Yes | X coordinate to translate.| | y | number | Yes | Yes | Y coordinate of the region.| ## PackingOption @@ -2271,8 +2498,9 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image.
Currently, the JPEG and WebP formats are supported. | +| format | string | Yes | Yes | Format of the packed image.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| +| bufferSize9+ | number | Yes | Yes | Buffer size, which is used to set the image size. The default value is 10 MB.| ## GetImagePropertyOptions7+ @@ -2299,8 +2527,14 @@ Describes the exchangeable image file format (EXIF) information of an image. | IMAGE_WIDTH | "ImageWidth" | Image width. | | GPS_LATITUDE | "GPSLatitude" | Image latitude. | | GPS_LONGITUDE | "GPSLongitude" | Image longitude. | -| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | -| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | +| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Shooting time, for example, 2022:09:06 15:48:00. | +| EXPOSURE_TIME9+ | "ExposureTime" | Exposure time, for example, 1/33 sec.| +| SCENE_TYPE9+ | "SceneType" | Shooting scene mode, for example, portrait, scenery, motion, and night sight. | +| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. | +| F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. | + ## ImageFormat9+ diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index f29975c5b4459acfd3d22e1a0f40b0579969ba24..924a6306618087d4589f5e33cf1c770e8c75c61f 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -47,7 +47,7 @@ Obtains an **[InputMethodController](#inputmethodcontroller)** instance. | Type | Description | | ----------------------------------------------- | ------------------------ | -| [InputMethodController](#inputmethodcontroller) | Returns the current **InputMethodController** instance.| +| [InputMethodController](#inputmethodcontroller) | Current **InputMethodController** instance.| **Example** @@ -67,7 +67,7 @@ Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. | Type | Description | | ----------------------------------------- | ---------------------------- | -| [InputMethodSetting](#inputmethodsetting8) | Returns the current **InputMethodSetting** instance.| +| [InputMethodSetting](#inputmethodsetting8) | Current **InputMethodSetting** instance.| **Example** @@ -94,15 +94,15 @@ Switches to another input method. This API can be used only in the stage model. **Example** ```js -inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"} ,(err,result) => { +inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'} ,(err,result) => { if (err) { - console.error("switchInputMethod err: " + JSON.stringify(err)); + console.error('switchInputMethod err: ' + JSON.stringify(err)); return; } if (result) { - console.info("Success to switchInputMethod.(callback)"); + console.info('Success to switchInputMethod.(callback)'); } else { - console.error("Failed to switchInputMethod.(callback)"); + console.error('Failed to switchInputMethod.(callback)'); } }); ``` @@ -129,14 +129,14 @@ Switches to another input method. This API can be used only in the stage model. ```js -inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"}).then((result) => { +inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'}).then((result) => { if (result) { - console.info("Success to switchInputMethod.(promise)"); + console.info('Success to switchInputMethod.(promise)'); } else { - console.error("Failed to switchInputMethod.(promise)"); + console.error('Failed to switchInputMethod.(promise)'); } }).catch((err) => { - console.error("switchInputMethod promise err: " + err); + console.error('switchInputMethod promise err: ' + err); }) ``` ## inputMethod.getCurrentInputMethod9+ @@ -151,7 +151,7 @@ Obtains the current input method. This API synchronously returns the **Inputmeth | Type | Description | | -------------------------------------------- | ------------------------ | -| [InputmethodProperty](#inputmethodproperty8) | **InputmethodProperty** instance of the current input method. | +| [InputmethodProperty](#inputmethodproperty8) | **InputmethodProperty** instance of the current input method.| **Example** @@ -183,13 +183,13 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ```js InputMethodController.stopInput((error, result) => { if (error) { - console.error("failed to stopInput because: " + JSON.stringify(error)); + console.error('failed to stopInput because: ' + JSON.stringify(error)); return; } if (result) { - console.info("Success to stopInput.(callback)"); + console.info('Success to stopInput.(callback)'); } else { - console.error("Failed to stopInput.(callback)"); + console.error('Failed to stopInput.(callback)'); } }); ``` @@ -214,12 +214,12 @@ Hides the keyboard. This API uses a promise to return the result. If any paramet ```js InputMethodController.stopInput().then((result) => { if (result) { - console.info("Success to stopInput.(promise)"); + console.info('Success to stopInput.(promise)'); } else { - console.error("Failed to stopInput.(promise)"); + console.error('Failed to stopInput.(promise)'); } }).catch((err) => { - console.error("stopInput promise err: " + err); + console.error('stopInput promise err: ' + err); }) ``` @@ -241,7 +241,7 @@ Shows this soft keyboard. This API uses an asynchronous callback to return the r ```js InputMethodController.showSoftKeyboard((err) => { - if (err == undefined) { + if (err === undefined) { console.info('showSoftKeyboard success'); } else { console.error('showSoftKeyboard failed because : ' + JSON.stringify(err)); @@ -292,7 +292,7 @@ Hides this soft keyboard. This API uses an asynchronous callback to return the r ```js InputMethodController.hideSoftKeyboard((err) => { - if (err == undefined) { + if (err === undefined) { console.info('hideSoftKeyboard success'); } else { console.error('hideSoftKeyboard failed because : ' + JSON.stringify(err)); @@ -342,19 +342,17 @@ Obtains a list of activated or deactivated input methods. This API uses an async | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ----------------------------- | | enable | boolean | Yes | Whether to return a list of activated input methods. The value **true** means to return a list of activated input methods, and **false** means to return a list of deactivated input methods. | -| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return a list of activated or deactivated input methods. | +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return a list of activated or deactivated input methods.| **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod(true, (err,data) => { if (err) { - console.error("listInputMethod failed because: " + JSON.stringify(err)); + console.error('listInputMethod failed because: ' + JSON.stringify(err)); return; } - console.log("listInputMethod success"); - this.imeList = data; + console.log('listInputMethod success'); }); ``` @@ -376,17 +374,15 @@ Obtains a list of activated or deactivated input methods. This API uses a promis | Type | Description | | ------------------------------------------------------------ | ----------------------------- | -| Promise> | Promise used to return a list of activated or deactivated input methods. | +| Promise> | Promise used to return a list of activated or deactivated input methods.| **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod(true).then((data) => { - console.info("listInputMethod success"); - this.imeList = data; + console.info('listInputMethod success'); }).catch((err) => { - console.error("listInputMethod promise err: " + err); + console.error('listInputMethod promise err: ' + err); }) ``` @@ -407,14 +403,12 @@ Obtains a list of installed input methods. This API uses an asynchronous callbac **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod((err,data) => { if (err) { - console.error("listInputMethod failed because: " + JSON.stringify(err)); + console.error('listInputMethod failed because: ' + JSON.stringify(err)); return; } - console.log("listInputMethod success"); - this.imeList = data; + console.log('listInputMethod success'); }); ``` @@ -435,12 +429,10 @@ Obtains a list of installed input methods. This API uses a promise to return the **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod().then((data) => { - console.info("listInputMethod success"); - this.imeList = data; + console.info('listInputMethod success'); }).catch((err) => { - console.error("listInputMethod promise err: " + err); + console.error('listInputMethod promise err: ' + err); }) ``` @@ -463,20 +455,20 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono ```js InputMethodSetting.displayOptionalInputMethod((err) => { if (err) { - console.error("displayOptionalInputMethod failed because: " + JSON.stringify(err)); + console.error('displayOptionalInputMethod failed because: ' + JSON.stringify(err)); return; } - console.info("displayOptionalInputMethod success"); + console.info('displayOptionalInputMethod success'); }); ``` ### displayOptionalInputMethod -displayOptionalInputMethod(): Promise<void> + displayOptionalInputMethod(): Promise<void> -Displays a dialog box for selecting an input method. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. + Displays a dialog box for selecting an input method. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. -**System capability**: SystemCapability.MiscServices.InputMethodFramework + **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -488,8 +480,8 @@ Displays a dialog box for selecting an input method. This API uses a promise to ```js InputMethodSetting.displayOptionalInputMethod().then(() => { - console.info("displayOptionalInputMethod success.(promise)"); + console.info('displayOptionalInputMethod success.(promise)'); }).catch((err) => { - console.error("displayOptionalInputMethod promise err: " + err); + console.error('displayOptionalInputMethod promise err: ' + err); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 55e702cd0501af092bbc7e0420f410ff81ed90c6..7ae35566725ea5fd3d489c29ea8b4d330695a534 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -46,6 +46,11 @@ Provides the constants. | 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.| +| CURSOR_UP9+ | number | Yes| No| The caret moves upward.| +| CURSOR_DOWN9+ | number | Yes| No| The caret moves downward.| +| CURSOR_LEFT9+ | number | Yes| No| The caret moves leftward.| +| CURSOR_RIGHT9+ | number | Yes| No| The caret moves rightward.| +| WINDOW_TYPE_INPUT_METHOD_FLOAT9+ | number | Yes| No| The input method is displayed in a floating window.| ## inputMethodEngine.getInputMethodEngine @@ -95,7 +100,7 @@ In the following API examples, you must first use [getInputMethodEngine](#getInp 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. +Listens for the input method binding event. This API uses a callback to return the result. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -119,7 +124,7 @@ Listens for the input method binding event. This API uses a callback to return t off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void -Cancels listening for the input method binding event. +Cancels listening for the input method binding event. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -135,14 +140,108 @@ Cancels listening for the input method binding event. **Example** ```js - InputMethodEngine.off('inputStart'); + InputMethodEngine.off('inputStart', (kbController, textInputClient) => { + console.log('delete inputStart notification.'); + }); + ``` + +### on('inputStop')9+ + +on(type: 'inputStop', callback: () => void): void + +Listens for the input method stop 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 **'inputStop'**, which indicates listening for the input method stop event.| +| callback | void | Yes | Callback used to return the result. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().on('inputStop', () => { + console.log('inputMethodEngine inputStop'); +}); + ``` + +### off('inputStop')9+ + +off(type: 'inputStop', callback: () => void): void + +Cancels listening for the input method stop 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 **'inputStop'**, which indicates listening for the input method stop event.| +| callback | void | Yes | Callback used to return the result. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().off('inputStop', () => { + console.log('inputMethodEngine delete inputStop notification.'); +}); + ``` + +### on('setCallingWindow')9+ + +on(type: 'setCallingWindow', callback: (wid:number) => void): void + +Listens for the window invocation setting 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 **'setCallingWindow'**, which indicates listening for the window invocation setting event.| +| callback | number | Yes | Window ID of the caller. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().on('setCallingWindow', (wid) => { + console.log('inputMethodEngine setCallingWindow'); +}); + ``` + +### off('setCallingWindow')9+ + +off(type: 'setCallingWindow', callback: (wid:number) => void): void + +Cancels listening for the window invocation setting 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 **'setCallingWindow'**, which indicates listening for the window invocation setting event.| +| callback | number | Yes | Window ID of the caller. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().off('setCallingWindow', () => { + console.log('inputMethodEngine delete setCallingWindow notification.'); +}); ``` ### on('keyboardShow'|'keyboardHide') on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void -Listens for an input method event. +Listens for an input method event. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -150,14 +249,17 @@ Listens for an input method event. | 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.| +| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the keyboard.
- The value **'keyboardHide'** means to listen for hiding of the keyboard. | | callback | void | No | Callback used to return the result. | **Example** ```js - InputMethodEngine.on('keyboardShow', (err) => { - console.info('keyboardShow'); + InputMethodEngine.on('keyboardShow', () => { + console.log('inputMethodEngine keyboardShow.'); + }); + InputMethodEngine.on('keyboardHide', () => { + console.log('inputMethodEngine keyboardHide.'); }); ``` @@ -165,7 +267,7 @@ Listens for an input method event. off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void -Cancels listening for an input method event. +Cancels listening for an input method event. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -173,13 +275,18 @@ Cancels listening for an input method event. | 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.| +| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the keyboard.
- The value **'keyboardHide'** means to listen for hiding of the keyboard.| | callback | void | No | Callback used to return the result. | **Example** ```js - InputMethodEngine.off('keyboardShow'); + InputMethodEngine.off('keyboardShow', () => { + console.log('inputMethodEngine delete keyboardShow notification.'); + }); + InputMethodEngine.off('keyboardHide', () => { + console.log('inputMethodEngine delete keyboardHide notification.'); + }); ``` @@ -191,7 +298,7 @@ In the following API examples, you must first use [createKeyboardDelegate](#crea 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. +Listens for a hard keyboard even. This API uses a callback to return the key information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -199,7 +306,7 @@ Listens for a hard keyboard even. This API uses a callback to return the key inf | 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.| +| 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.| @@ -207,8 +314,15 @@ Listens for a hard keyboard even. This API uses a callback to return the key inf **Example** ```js - KeyboardDelegate.on('keyDown', (event) => { - console.info('keyDown'); + KeyboardDelegate.on('keyUp', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyUp):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyUp):' + JSON.stringify(keyEvent.keyAction)); + return true; + }); + KeyboardDelegate.on('keyDown', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyDown):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyDown):' + JSON.stringify(keyEvent.keyAction)); + return true; }); ``` @@ -216,7 +330,7 @@ Listens for a hard keyboard even. This API uses a callback to return the key inf off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void -Cancels listening for a hard keyboard even. +Cancels listening for a hard keyboard even. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -224,20 +338,27 @@ Cancels listening for a hard keyboard even. | 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.| +| 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** ```js - KeyboardDelegate.off('keyDown'); + KeyboardDelegate.off('keyUp', (keyEvent) => { + console.log('delete keyUp notification.'); + return true; + }); + KeyboardDelegate.off('keyDown', (keyEvent) => { + console.log('delete keyDown notification.'); + return true; + }); ``` ### 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. +Listens for cursor context changes. This API uses a callback to return the cursor information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -253,18 +374,18 @@ Listens for cursor context changes. This API uses a callback to return the curso **Example** ```js - KeyboardDelegate.on('cursorContextChange', (x, y, height) => { - console.info('cursorContextChange'); + console.log('inputMethodEngine cursorContextChange x:' + x); + console.log('inputMethodEngine cursorContextChange y:' + y); + console.log('inputMethodEngine cursorContextChange height:' + height); }); - ``` ### off('cursorContextChange') off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) => void): void -Cancels listening for cursor context changes. +Cancels listening for cursor context changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -279,15 +400,15 @@ Cancels listening for cursor context changes. **Example** ```js - -KeyboardDelegate.off('cursorContextChange'); - +KeyboardDelegate.off('cursorContextChange', (x, y, height) => { + console.log('delete cursorContextChange notification.'); +}); ``` ### 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. +Listens for text selection changes. This API uses a callback to return the text selection information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -301,18 +422,19 @@ Listens for text selection changes. This API uses a callback to return the text **Example** ```js - KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { - console.info('selectionChange'); + console.log('inputMethodEngine beforeEach selectionChange oldBegin:' + oldBegin); + console.log('inputMethodEngine beforeEach selectionChange oldEnd:' + oldEnd); + console.log('inputMethodEngine beforeEach selectionChange newBegin:' + newBegin); + console.log('inputMethodEngine beforeEach selectionChange newEnd:' + newEnd); }); - ``` ### off('selectionChange') off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void -Cancels listening for text selection changes. +Cancels listening for text selection changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -326,9 +448,9 @@ Cancels listening for text selection changes. **Example** ```js - -KeyboardDelegate.off('selectionChange'); - +KeyboardDelegate.off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { + console.log('delete selectionChange notification.'); +}); ``` @@ -336,7 +458,7 @@ KeyboardDelegate.off('selectionChange'); on(type: 'textChange', callback: (text: string) => void): void -Listens for text changes. This API uses a callback to return the current text content. +Listens for text changes. This API uses a callback to return the current text content. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -350,18 +472,16 @@ Listens for text changes. This API uses a callback to return the current text co **Example** ```js - KeyboardDelegate.on('textChange', (text) => { - console.info('textChange'); + console.log('inputMethodEngine textChange. text:' + text); }); - ``` ### off('textChange') off(type: 'textChange', callback?: (text: string) => void): void -Cancels listening for text changes. +Cancels listening for text changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -375,7 +495,9 @@ Cancels listening for text changes. **Example** ```js -KeyboardDelegate.off('textChange'); +keyboardDelegate.off('textChange', (text) => { + console.log('delete textChange notification. text:' + text); +}); ``` ## KeyboardController @@ -386,7 +508,7 @@ In the following API examples, you must first use [inputStart](#inputStart) to o hideKeyboard(callback: AsyncCallback<void>): void -Hides the keyboard. This API uses an asynchronous callback to return the result. +Hides the keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -400,28 +522,39 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ```js - KeyboardController.hideKeyboard(()=>{ - }); +KeyboardController.hideKeyboard((err) => { + if (err === undefined) { + console.error('hideKeyboard callback result---err: ' + err.msg); + return; + } + console.log('hideKeyboard callback.'); +}); ``` ### hideKeyboard hideKeyboard(): Promise<void> -Hides the keyboard. This API uses an asynchronous callback to return the result. +Hides the keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| ---------------- | -------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ---------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - KeyboardController.hideKeyboard(); +async function InputMethodEngine() { + await KeyboardController.hideKeyboard().then(() => { + console.info('hideKeyboard promise.'); + }).catch((err) => { + console.info('hideKeyboard promise err: ' + err.msg); + }); +} ``` ## TextInputClient @@ -432,7 +565,7 @@ In the following API examples, you must first use [inputStart](#inputStart) to o 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. +Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -446,16 +579,21 @@ Obtains the specific-length text before the cursor. This API uses an asynchronou **Example** ```js - TextInputClient.getForward(5,(text) =>{ - console.info("text = " + text); - }); + var length = 1; + TextInputClient.getForward(length, (err, text) => { + if (err === undefined) { + console.error('getForward callback result---err: ' + err.msg); + return; + } + console.log('getForward callback result---text: ' + text); + }); ``` ### getForward getForward(length:number): Promise<string> -Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. +Obtains the specific-length text before the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -474,15 +612,21 @@ Obtains the specific-length text before the cursor. This API uses an asynchronou **Example** ```js - var text = TextInputClient.getForward(5); - console.info("text = " + text); + async function InputMethodEngine() { + var length = 1; + await TextInputClient.getForward(length).then((text) => { + console.info('getForward promise result---res: ' + text); + }).catch((err) => { + console.error('getForward promise err: ' + err.msg); + }); + } ``` ### 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. +Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -496,8 +640,13 @@ Obtains the specific-length text after the cursor. This API uses an asynchronous **Example** ```js - TextInputClient.getBackward(5,(text)=>{ - console.info("text = " + text); + var length = 1; + TextInputClient.getBackward(length, (err, text) => { + if (err === undefined) { + console.error('getBackward callback result---err: ' + err.msg); + return; + } + console.log('getBackward callback result---text: ' + text); }); ``` @@ -505,7 +654,7 @@ Obtains the specific-length text after the cursor. This API uses an asynchronous getBackward(length:number): Promise<string> -Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. +Obtains the specific-length text after the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -524,15 +673,21 @@ Obtains the specific-length text after the cursor. This API uses an asynchronous **Example** ```js - var text = TextInputClient.getBackward(5); - console.info("text = " + text); + async function InputMethodEngine() { + var length = 1; + await TextInputClient.getBackward(length).then((text) => { + console.info('getBackward promise result---res: ' + text); + }).catch((err) => { + console.error('getBackward promise err: ' + err.msg); + }); + } ``` ### 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. +Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -546,15 +701,24 @@ Deletes the fixed-length text before the cursor. This API uses an asynchronous c **Example** ```js - TextInputClient.deleteForward(5,(isSuccess)=>{ - console.info("isSuccess = " + isSuccess); + var length = 1; + TextInputClient.deleteForward(length, (err, result) => { + if (err === undefined) { + console.error('deleteForward callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to deleteForward.(callback) '); + } else { + console.error('Failed to deleteForward.(callback) '); + } }); ``` ### deleteForward deleteForward(length:number): Promise<boolean> -Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text before the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -573,15 +737,25 @@ Deletes the fixed-length text before the cursor. This API uses an asynchronous c **Example** ```js -var isSuccess = TextInputClient.deleteForward(5); - console.info("isSuccess = " + isSuccess); +async function InputMethodEngine() { + var length = 1; + await TextInputClient.deleteForward(length).then((result) => { + if (result) { + console.info('Success to deleteForward.(promise) '); + } else { + console.error('Failed to deleteForward.(promise) '); + } + }).catch((err) => { + console.error('deleteForward promise err: ' + err.msg); + }); +} ``` ### 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. +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -595,22 +769,30 @@ Deletes the fixed-length text after the cursor. This API uses an asynchronous ca **Example** ```js - - TextInputClient.deleteBackward(5, (isSuccess)=>{ - console.info("isSuccess = " + isSuccess); +var length = 1; +TextInputClient.deleteBackward(length, (err, result) => { + if (err === undefined) { + console.error('deleteBackward callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to deleteBackward.(callback) '); + } else { + console.error('Failed to deleteBackward.(callback) '); + } }); - ``` ### deleteBackward deleteBackward(length:number): Promise<boolean> -Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | length | number | Yes| Text length.| @@ -624,16 +806,24 @@ Deletes the fixed-length text after the cursor. This API uses an asynchronous ca **Example** ```js - - var isSuccess = TextInputClient.deleteBackward(5); - console.info("isSuccess = " + isSuccess); - +async function InputMethodEngine() { + var length = 1; + await TextInputClient.deleteBackward(length).then((result) => { + if (result) { + console.info('Success to deleteBackward.(promise) '); + } else { + console.error('Failed to deleteBackward.(promise) '); + } + }).catch((err) => { + console.error('deleteBackward promise err: ' + err.msg); + }); +} ``` ### 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. +Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -647,18 +837,24 @@ Sets the Enter key to send the text to its target. This API uses an asynchronous **Example** ```js - - TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT,(isSuccess)=>{ - console.info("isSuccess = " + isSuccess); +TextInputClient.sendKeyFunction(keyFunction, (err, result) => { + if (err === undefined) { + console.error('sendKeyFunction callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to sendKeyFunction.(callback) '); + } else { + console.error('Failed to sendKeyFunction.(callback) '); + } }); - ``` ### sendKeyFunction sendKeyFunction(action:number): Promise<boolean> -Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. +Sets the Enter key to send the text to its target. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -677,15 +873,24 @@ Sets the Enter key to send the text to its target. This API uses an asynchronous **Example** ```js - var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT); - console.info("isSuccess = " + isSuccess); + async function InputMethodEngine() { + await client.sendKeyFunction(keyFunction).then((result) => { + if (result) { + console.info('Success to sendKeyFunction.(promise) '); + } else { + console.error('Failed to sendKeyFunction.(promise) '); + } + }).catch((err) => { + console.error('sendKeyFunction promise err:' + err.msg); + }); + } ``` ### insertText insertText(text:string, callback: AsyncCallback<boolean>): void -Inserts text. This API uses an asynchronous callback to return the result. +Inserts text. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -699,18 +904,24 @@ Inserts text. This API uses an asynchronous callback to return the result. **Example** ```js - -TextInputClient.insertText("test", (isSuccess)=>{ - console.info("isSuccess = " + isSuccess); +TextInputClient.insertText('test', (err, result) => { + if (err === undefined) { + console.error('insertText callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to insertText.(callback) '); + } else { + console.error('Failed to insertText.(callback) '); + } }); - ``` ### insertText insertText(text:string): Promise<boolean> -Inserts text. This API uses an asynchronous callback to return the result. +Inserts text. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -729,15 +940,24 @@ Inserts text. This API uses an asynchronous callback to return the result. **Example** ```js - var isSuccess = TextInputClient.insertText("test"); - console.info("isSuccess = " + isSuccess); + async function InputMethodEngine() { + await TextInputClient.insertText('test').then((result) => { + if (result) { + console.info('Success to insertText.(promise) '); + } else { + console.error('Failed to insertText.(promise) '); + } + }).catch((err) => { + console.error('insertText promise err: ' + err.msg); + }); + } ``` ### getEditorAttribute getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void -Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. +Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -750,15 +970,21 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to **Example** ```js - TextInputClient.getEditorAttribute((EditorAttribute)=>{ - }); + TextInputClient.getEditorAttribute((err, editorAttribute) => { + if (err === undefined) { + console.error('getEditorAttribute callback result---err: ' + err.msg); + return; + } + console.log('editorAttribute.inputPattern(callback): ' + JSON.stringify(editorAttribute.inputPattern)); + console.log('editorAttribute.enterKeyType(callback): ' + JSON.stringify(editorAttribute.enterKeyType)); + }); ``` ### getEditorAttribute -getEditorAttribute(): EditorAttribute +getEditorAttribute(): Promise<EditorAttribute> -Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. +Obtains the attribute of the edit box. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -766,14 +992,79 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<[EditorAttribute](#EditorAttribute)> | Promise used to return the attribute of the edit box. | +| Promise<[EditorAttribute](#EditorAttribute)> | Promise used to return the attribute of the edit box. | **Example** ```js - var EditorAttribute = TextInputClient.getEditorAttribute(); + async function InputMethodEngine() { + await TextInputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern(promise): ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType(promise): ' + JSON.stringify(editorAttribute.enterKeyType)); + }).catch((err) => { + console.error('getEditorAttribute promise err: ' + err.msg); + }); + } ``` +### moveCursor9+ + +moveCursor(direction: number, callback: AsyncCallback<void>): void + +Moves the cursor. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | -------------- | +| direction | number | Yes | Direction in which the cursor moves.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => { + if (err === undefined) { + console.error('moveCursor callback result---err: ' + err.msg); + return; + } +}); +``` + +### moveCursor9+ + +moveCursor(direction: number): Promise<void> + +Moves the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------- | +| direction | number | Yes | Direction in which the cursor moves.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +async function InputMethodEngine() { + await TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then(async (err) => { + console.log('moveCursor success'); + }).catch((err) => { + console.error('moveCursor success err: ' + err.msg); + }); +} + ``` + ## EditorAttribute Describes the attribute of the edit box. diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 07084623fbe78c307fdc787b1715b398e3d97675..9fdcb88e96a336e19a87efab9c9856af746df558 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -101,7 +101,7 @@ This is a system API. inputMonitor.off("touch"); ``` -off(type: "mouse", receiver?:Callback):void +off(type: "mouse", receiver?:Callback\):void Stops listening for global mouse events. diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index fcf2858aa7b4a1adda999a0e1bf0850495c0d00f..79cdf3ac5627984eba2f03e7eb37b9cc7137de4a 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -64,7 +64,7 @@ Creates a Locale object. | Name | Type | Mandatory | Description | | ------- | ------------- | ---- | ---------------------------- | | locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -| options | LocaleOptions | No | Options for creating the **Locale** object. | +| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | **Example** ``` @@ -181,7 +181,7 @@ Creates a **DateTimeOptions** object for the specified locale. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [DateTimeOptions](#datetimeoptions) | No | Options for creating a **DateTimeFormat** object. | +| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | **Example** ``` @@ -265,7 +265,7 @@ Obtains the formatting options for **DateTimeFormat** object. | Type | Description | | ----------------------------------- | ----------------------------- | -| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| +| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| **Example** ``` @@ -332,7 +332,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [NumberOptions](#numberoptions) | No | Options for creating a **NumberFormat** object. | +| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | **Example** ``` @@ -380,7 +380,7 @@ Obtains the options of the **NumberFormat** object. | Type | Description | | ------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| +| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| **Example** @@ -404,7 +404,7 @@ Provides the device capability. | 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 **narrow**.| -| unitUsage8+ | 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**.| +| 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**.| @@ -449,7 +449,7 @@ Creates a Collator object. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [CollatorOptions](#collatoroptions) | No | Options for creating a **Collator** object. | +| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | **Example** ``` @@ -497,9 +497,10 @@ Returns properties reflecting the locale and collation options of a **Collator** | Type | Description | | ----------------------------------- | ----------------- | -| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| +| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| **Example** + ``` var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); @@ -552,7 +553,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [PluralRulesOptions](#pluralrulesoptions) | No | Options for creating a **PluralRules** object. | +| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | **Example** ``` @@ -634,7 +635,7 @@ Creates a **RelativeTimeFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No | Options for creating a **RelativeTimeFormat** object. | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | **Example** ``` @@ -710,7 +711,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. | Type | Description | | ---------------------------------------- | --------------------------------- | -| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| +| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index 3a711c0ea13132547c4fc2bb9cc76066f71ab0ee..dd4ac0b22afb7e0101579db5b6d639504f58197d 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -96,7 +96,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode' | KEYCODE_EQUALS | number | Yes| No| Key =| | KEYCODE_LEFT_BRACKET | number | Yes| No| Key [| | KEYCODE_RIGHT_BRACKET | number | Yes| No| Key ]| -| KEYCODE_BACKSLASH | number | Yes| No| Key \| +| KEYCODE_BACKSLASH | number | Yes| No| Key \\| | KEYCODE_SEMICOLON | number | Yes| No| Key ;| | KEYCODE_APOSTROPHE | number | Yes| No| Key ' | | KEYCODE_SLASH | number | Yes| No| Key /| diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index fca68b5554d6239a03415892d68570dc1b4e8574..b29a380a5b1b2e8afb4d41687a659dc29db4344c 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -229,7 +229,7 @@ Enumerates the codec MIME types. | VIDEO_MPEG2 | 'video/mpeg2' | Video in MPEG-2 format. | | VIDEO_MPEG4 | 'video/mp4v-es' | Video in MPEG-4 format. | | VIDEO_VP8 | 'video/x-vnd.on2.vp8' | Video in VP8 format. | -| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.| +| AUDIO_AAC | 'audio/mp4a-latm' | Audio in MP4A-LATM format.| | AUDIO_VORBIS | 'audio/vorbis' | Audio in Vorbis format. | | AUDIO_FLAC | 'audio/flac' | Audio in FLAC format. | @@ -241,16 +241,16 @@ Enumerates the media description keys. | Name | Value | Description | | ------------------------ | --------------- | ------------------------------------------------------------ | -| 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_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_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_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. | ## BufferingInfoType8+ @@ -442,10 +442,10 @@ function printfDescription(obj) { } } -audioPlayer.getTrackDescription((error, arrlist) => { - if (arrlist != null) { - for (let i = 0; i < arrlist.length; i++) { - printfDescription(arrlist[i]); +audioPlayer.getTrackDescription((error, arrList) => { + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); } } else { console.log(`audio getTrackDescription fail, error:${error}`); @@ -478,9 +478,9 @@ function printfDescription(obj) { } } let arrayDescription = null -audioPlayer.getTrackDescription().then((arrlist) => { - if (arrlist != null) { - arrayDescription = arrlist; +audioPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; } else { console.log('audio getTrackDescription fail'); } @@ -1235,10 +1235,10 @@ function printfDescription(obj) { } } -videoPlayer.getTrackDescription((error, arrlist) => { - if ((arrlist) != null) { - for (let i = 0; i < arrlist.length; i++) { - printfDescription(arrlist[i]); +videoPlayer.getTrackDescription((error, arrList) => { + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); } } else { console.log(`video getTrackDescription fail, error:${error}`); @@ -1272,9 +1272,9 @@ function printfDescription(obj) { } let arrayDescription; -videoPlayer.getTrackDescription().then((arrlist) => { - if (arrlist != null) { - arrayDescription = arrlist; +videoPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; } else { console.log('video getTrackDescription fail'); } @@ -1618,10 +1618,10 @@ function printfItemDescription(obj, key) { console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey]. } let audioPlayer = media.createAudioPlayer(); -audioPlayer.getTrackDescription((error, arrlist) => { - if (arrlist != null) { - for (let i = 0; i < arrlist.length; i++) { - printfItemDescription(arrlist[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. +audioPlayer.getTrackDescription((error, arrList) => { + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. } } else { console.log(`audio getTrackDescription fail, error:${error}`); @@ -2533,8 +2533,8 @@ Enumerates the container format types (CFTs). | Name | Value | Description | | ----------- | ----- | --------------------- | -| CFT_MPEG_4 | "mp4" | Video container format MPEG-4.| -| CFT_MPEG_4A | "m4a" | Audio container format M4A.| +| 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-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 50057062701f1ddbe0b058dc79e957c1a47e63a3..189042b1f1df1727423c65c0a226b11ae473db2a 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -42,18 +42,18 @@ Registers a listener to observe the mission status. **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); - - ``` +``` ## missionManager.unregisterMissionListener @@ -77,21 +77,22 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid, (error) => { - console.log("unregisterMissionListener"); + console.log("unregisterMissionListener"); }) - ``` +``` ## missionManager.unregisterMissionListener @@ -120,21 +121,22 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} - }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); - - missionManager.unregisterMissionListener(listenerid).catch(function (err){ - console.log(err); - }); - ``` +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + }; + console.log("registerMissionListener") + var listenerid = missionManager.registerMissionListener(listener); + + missionManager.unregisterMissionListener(listenerid).catch(function (err) { + console.log(err); + }); +``` ## missionManager.getMissionInfo diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index ec63d11121dcd5138d11d7a2e1898833deaaf9c7..da2443a7c87c363ae79085a9b0dfeda4f7f5af99 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -47,7 +47,7 @@ Obtains the default active data network. This API uses a promise to return the r **System capability**: SystemCapability.Communication.NetManager.Core -**Return Value** +**Return value** | Type | Description | | --------------------------------- | ------------------------------------- | @@ -61,11 +61,37 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` +## connection.getDefaultNetSync + +getDefaultNetSync(): NetHandle; + +Obtains the default active data network in synchronous mode. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------- | ---------------------------------- | +| NetHandle | Handle of the default active data network.| + +**Example** + +```js +let netHandle = connection.getDefaultNetSync(); +``` + + ## connection.hasDefaultNet hasDefaultNet(callback: AsyncCallback\): void Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. +The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. + +**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core @@ -89,10 +115,13 @@ connection.hasDefaultNet(function (error, has) { hasDefaultNet(): Promise\ Checks whether the default data network is activated. This API uses a promise to return the result. +The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. + +**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core -**Return Value** +**Return value** | Type | Description | | ----------------- | ----------------------------------------------- | @@ -117,6 +146,7 @@ Obtains the list of all active data networks. This API uses an asynchronous call **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result.| @@ -141,7 +171,8 @@ Obtains the list of all active data networks. This API uses a promise to return **System capability**: SystemCapability.Communication.NetManager.Core -**Return Value** +**Return value** + | Type| Description| | -------- | -------- | | Promise<Array<[NetHandle](#nethandle)>> | Promise used to return the result.| @@ -158,7 +189,7 @@ connection.getAllNets().then(function (nets) { getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void -Obtains connection properties of the network corresponding to given network handle. This API uses an asynchronous callback to return the result. +Obtains connection properties of the network corresponding to the given network handle. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -198,7 +229,7 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi | --------- | ----------------------- | ---- | ---------------- | | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| -**Return Value** +**Return value** | Type | Description | | ------------------------------------------------------- | --------------------------------- | @@ -258,7 +289,7 @@ Obtains capability information of the network corresponding to **netHandle**. Th | --------- | ----------------------- | ---- | ---------------- | | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| -**Return Value** +**Return value** | Type | Description | | --------------------------------------------- | --------------------------------- | @@ -285,6 +316,7 @@ Reports connection of the data network. This API uses an asynchronous callback t **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| @@ -312,11 +344,13 @@ Reports connection of the data network. This API uses a promise to return the re **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -**Return Value** +**Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| @@ -343,6 +377,7 @@ Reports disconnection of the data network. This API uses an asynchronous callbac **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| @@ -370,11 +405,13 @@ Reports disconnection of the data network. This API uses a promise to return the **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| -**Return Value** +**Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| @@ -432,7 +469,7 @@ Resolves the host name by using the default network to obtain all IP addresses. | ------ | ------ | ---- | ------------------ | | host | string | Yes | Host name to be resolved.| -**Return Value** +**Return value** | Type | Description | | ------------------------------------------- | ----------------------------- | @@ -561,7 +598,7 @@ Obtains the handle of the network specified by **netSpecifier**. | netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. | | timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.| -**Return Value** +**Return value** | Type | Description | | ------------------------------- | -------------------- | @@ -784,6 +821,108 @@ 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; + +Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------ | ---- | -------------------------------| +| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +connection.getDefaultNet().then(function (netHandle) { + var tcp = socket.constructTCPSocketInstance(); + var udp = socket.constructUDPSocketInstance(); + let socketType = "xxxx"; + if (socketType == "TCPSocket") { + tcp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + netHandle.bindSocket(tcp, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }) + } else { + udp.on('message', callback); + udp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + udp.on('message', (data) => { + console.log(JSON.stringify(data)) + }); + netHandle.bindSocket(udp, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }); + }) + } +} +``` + +### bindSocket + +bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\; + +Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | --------------------- | ---- | ------------------------------ | +| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes | **TCPSocket** or **UDPSocket** object.| + +**Return value** + +| Type | Description | +| -------------- | ---------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +connection.getDefaultNet().then(function (netHandle) { + var tcp = socket.constructTCPSocketInstance(); + var udp = socket.constructUDPSocketInstance(); + let socketType = "xxxx"; + if(socketType == "TCPSocket") { + tcp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + netHandle.bindSocket(tcp).then(err, data) { + console.log(JSON.stringify(data)) + }) + } else { + udp.on('message', callback); + udp.bind({ + address: "xxxx", port: xxxx, family: xxxx + }, err => { + udp.on('message', (data) => { + console.log(JSON.stringify(data)) + }); + netHandle.bindSocket(tcp).then(err, data) { + console.log(JSON.stringify(data)) + }); + }) + } +} +``` + + ### getAddressesByName getAddressesByName(host: string, callback: AsyncCallback\>): void @@ -829,7 +968,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre | ------ | ------ | ---- | ------------------ | | host | string | Yes | Host name to be resolved.| -**Return Value** +**Return value** | Type | Description | | ------------------------------------------- | ----------------------------- | @@ -891,7 +1030,7 @@ Resolves the host name by using the corresponding network to obtain the first IP | ------ | ------ | ---- | ------------------ | | host | string | Yes | Host name to be resolved.| -**Return Value** +**Return value** | Type | Description | | ----------------------------------- | ------------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..bf132f3c63710fc83b04a3411eb2477f2fe8b855 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -0,0 +1,301 @@ +# Ethernet Connection Management + +The Ethernet Connection Management module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. + +> **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. + +## Modules to Import + +```js +import ethernet from '@ohos.net.ethernet' +``` + +## ethernet.setIfaceConfig + +setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void; + +Sets the network interface configuration. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------------ | +| iface | string | Yes | Name of the network interface. | +| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Example** + +```js +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", + gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, + (error) => { + if (error) { + console.log("setIfaceConfig callback error = " + error); + } else { + console.log("setIfaceConfig callback ok "); + } + }); +``` + +## ethernet.setIfaceConfig + +setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\; + +Sets the network interface configuration. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------- | ---- | ------------------------ | +| iface | string | Yes | Name of the network interface. | +| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", + gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { + console.log("setIfaceConfig promiss ok "); +}).catch((error) => { + console.log("setIfaceConfig promiss error = " + error); +}); +``` + +## ethernet.getIfaceConfig + +getIfaceConfig(iface: string, callback: AsyncCallback\): void; + +Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | ----- | ------------ | +| iface | string | Yes | Name of the network interface.| +| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the configuration. | + +**Example** + +```js +ethernet.getIfaceConfig("eth0", (error, value) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + value.mode); + console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); + } +}); +``` + +## ethernet.getIfaceConfig + +getIfaceConfig(iface: string): Promise\; + +Obtains the configuration of a network interface. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------ | +| iface | string | Yes | Name of the network interface.| + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------------------------- | +| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the configuration. | + +**Example** + +```js +ethernet.getIfaceConfig("eth0").then((data) => { + console.log("getIfaceConfig promiss mode = " + data.mode); + console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); + console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); + console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); + console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); + console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); +}).catch((error) => { + console.log("getIfaceConfig promiss error = " + error); +}); +``` + +## ethernet.isIfaceActive + +isIfaceActive(iface?: string, callback: AsyncCallback\): void; + +Checks whether a network interface is active. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------- | +| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| + +**Example** + +```js +ethernet.isIfaceActive("eth0", (error, value) => { + if (error) { + console.log("whether2Activate callback error = " + error); + } else { + console.log("whether2Activate callback = " + value); + } +}); +``` + +## ethernet.isIfaceActive + +isIfaceActive(iface?: string): Promise\; + +Checks whether a network interface is active. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| + +**Return value** + +| Type | Description | +| ----------------| ------------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| + +**Example** + +```js +ethernet.isIfaceActive("eth0").then((data) => { + console.log("isIfaceActive promiss = " + data); +}).catch((error) => { + console.log("isIfaceActive promiss error = " + error); +}); +``` + +## ethernet.getAllActiveIfaces + +getAllActiveIfaces(callback: AsyncCallback\>): void; + +Obtains all active network interfaces. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return all the active network interface names obtained.| + +**Example** + +```js +ethernet.getAllActiveIfaces((error, value) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback value.length = " + value.length); + for (let i = 0; i < value.length; i++) { + console.log("getAllActiveIfaces callback = " + value[i]); + } + } +}); +``` + +## ethernet.getAllActiveIfaces + +getAllActiveIfaces(): Promise\>; + +Obtains all active network interfaces. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +**Return value** + +| Type | Description | +| ------------------------------ | ----------------------------------------------- | +| Promise\> | Promise used to return all the active network interface names obtained.| + +**Example** + +```js +ethernet.getAllActiveIfaces().then((data) => { + console.log("getAllActiveIfaces promiss data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces promiss = " + data[i]); + } +}).catch((error) => { + console.log("getAllActiveIfaces promiss error = " + error); +}); +``` + +## InterfaceConfiguration + +Defines the network configuration for the Ethernet connection. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| mode | [IPSetMode](#ipsetmode) | Configuration mode of the Ethernet connection.| +| ipAddr | string | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| +| route | string | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| gateway | string | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| netMask | string | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| dnsServers | string | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| + +## IPSetMode + +Defines the configuration mode of the Ethernet connection. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| STATIC | 0 | Static configuration.| +| DHCP | 1 | Dynamic configuration.| diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..4537266a60faa11243140aee10a7f9d9a36bfa7b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-policy.md @@ -0,0 +1,1120 @@ +# Network Policy Management + +The Network Policy Management module provides APIs for managing network policies, through which you can control and manage the data volume used. + +> **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. + +## Modules to Import + +```js +import policy from '@ohos.net.policy' +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void + +Sets a background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean): Promise\ + +Sets a background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicy + +getBackgroundPolicy(callback: AsyncCallback\): void; + +Obtains the background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If **true** is returned, applications running in the background are allowed to use mobile data.| + +**Example** + +```js +policy.getBackgroundPolicy((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.getBackgroundPolicy + +getBackgroundPolicy(): Promise\; + +Obtains the background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.getBackgroundPolicy().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void; + +Sets an application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; + +Sets an application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number, callback: AsyncCallback\): void; + +Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number): Promise\; + +Obtains an application-specific network policy by **uid**. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetUidPolicy](#netuidpolicy)> | Promise used to return the result.| + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getUidsByPolicy + +getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getUidsByPolicy + +function getUidsByPolicy(policy: NetUidPolicy): Promise\>; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(callback: AsyncCallback\>): void; + +Obtains the network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getNetQuotaPolicies((err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(): Promise\>; + +Obtains the network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getNetQuotaPolicies().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void; + +Sets an array of network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\): Promise\; + +Sets an array of network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string, callback: AsyncCallback\): void; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string): Promise\; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam).then((err, data){ + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void; + +Checks whether an application is allowed to access metered networks. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean): Promise\; + +Checks whether an application is allowed to access metered networks. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void; + +Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the given network, and **false** means the opposite.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string): Promise\; + +Checks whether an application is allowed to access the given network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setDeviceIdleAllowlist + +setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; + +Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| +| callback | callback: AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setDeviceIdleAllowlist + +setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\; + +Sets whether to add an application to the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getDeviceIdleAllowlist + +getDeviceIdleAllowList(callback: AsyncCallback\>): void; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getDeviceIdleAllowList((err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getDeviceIdleAllowlist + +getDeviceIdleAllowList(): Promise\>; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getDeviceIdleAllowList().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void; + +Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number): Promise\; + +Obtains the background network policies configured for the given application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Promise used to return the result.| + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.resetPolicies + +resetPolicies(iccid: string, callback: AsyncCallback\): void; + +Resets the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = iccid +policy.resetPolicies(this.firstParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.resetPolicies + +resetPolicies(iccid: string): Promise\; + +Resets the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((err, data) { + +}) +this.firstParam = iccid +policy.resetPolicies(this.firstParam).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void; + +Updates a reminder policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\; + +Updates a reminder policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.on + +Functions as the handle to a network policy. + +### on('netUidPolicyChange') + +on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; + +Subscribes to policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidPolicyChange | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.| +| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netUidRuleChange') + +on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; + +Subscribes to rule changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidRuleChange | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.| +| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange: ' + JSON.stringify(data)); +}) +``` + +### on('netMeteredIfacesChange') + +on(type: "netMeteredIfacesChange", callback: Callback\>): void; + +Subscribes to metered network name (specified by **iface**) changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netMeteredIfacesChange | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered network name change event.| +| callback | Callback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); +}) +``` + +### on('netQuotaPolicyChange') + +on(type: "netQuotaPolicyChange", callback: Callback\>): void; + +Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.| +| callback | Callback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netBackgroundPolicyChange') + +on(type: "netBackgroundPolicyChange", callback: Callback\): void; + +Subscribes to background network policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netBackgroundPolicyChange | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.| +| callback | Callback\ | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); +}) +``` + +## NetBackgroundPolicy + +Enumerates the background network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_BACKGROUND_POLICY_NONE | 0 | Default policy.| +| NET_BACKGROUND_POLICY_ENABLE | 1 | Applications running in the background are allowed to access metered networks.| +| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access metered networks.| +| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | Only applications on the device idle allowlist are allowed to access metered networks when they are running in the background.| + +## NetQuotaPolicy + +Defines a network quota policy. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Network type.| +| iccid | string | Identifier of the SIM card on the metered cellular network. It is not used for Wi-Fi networks.| +| ident | string | Identifier of the SIM card on the metered cellular network. It is used for Wi-Fi networks. It is used together with **iccid**.| +| periodDuration | string | Start time of metering.| +| warningBytes | number | Data volume threshold for generating an alarm.| +| limitBytes | number | Data volume quota.| +| lastWarningRemind | string | Last time when an alarm was generated.| +| lastLimitRemind | string | Last time when the quota was exhausted.| +| metered | string | Whether the network is a metered network.| +| limitAction | [LimitAction](#limitaction) | Action to take when the data volume quota is reached.| + +## LimitAction + +Enumerates the actions that can be taken when the data volume quota is reached. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| LIMIT_ACTION_NONE | -1 | Default action.| +| LIMIT_ACTION_DISABLE | 0 | Internet access is disabled.| +| LIMIT_ACTION_AUTO_BILL| 1 | Users will be automatically charged for the data volume they use.| + +## NetUidRule + +Enumerates the metered network rules. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_RULE_NONE | 0 | Default rule.| +| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | Applications running in the foreground are allowed to access metered networks.| +| NET_RULE_ALLOW_METERED | 2 | Applications are allowed to access metered networks.| +| NET_RULE_REJECT_METERED | 4 | Applications are not allowed to access metered networks.| +| NET_RULE_ALLOW_ALL | 32 | Applications are allowed to access all networks (metered or non-metered).| +| NET_RULE_REJECT_ALL | 64 | Applications are not allowed to access any networks (metered or non-metered).| + +## RemindType + +Enumerates the reminder types. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | - | ------- | +| REMIND_TYPE_WARNING | 1 | Warning.| +| REMIND_TYPE_LIMIT | 2 | Limit.| + +## NetUidPolicy + +Enumerates the application-specific network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_POLICY_NONE | 0 | Default network policy.| +| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | Applications running in the background are allowed to access metered networks.| +| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | Applications running in the background are not allowed to access metered networks.| diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..23284aeb1715a3f8aed9ec7b2d79ad55d1408319 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -0,0 +1,746 @@ +# Network Sharing Management + +The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. + +> **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. + +## Modules to Import + +```js +import sharing from '@ohos.net.sharing' +``` + +## sharing.isSharingSupported + +isSharingSupported(callback: AsyncCallback\): void + +Checks whether network sharing is supported. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharingSupported((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.isSharingSupported + +isSharingSupported(): Promise\ + +Checks whether network sharing is supported. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharingSupported().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.isSharing + +isSharing(callback: AsyncCallback\): void + +Checks whether network sharing is in progress. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharing((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.isSharing + +isSharing(): Promise\ + +Checks whether network sharing is in progress. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharing().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.startSharing + +startSharing(type: SharingIfaceType, callback: AsyncCallback\): void + +Starts network sharing of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.startSharing + +startSharing(type: SharingIfaceType): Promise\ + +Starts network sharing of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.startSharing(SharingIfaceType.SHARING_WIFI).then(() => { + console.log("start wifi sharing successful"); +}).catch(error => { + console.log("start wifi sharing failed"); +}); +``` + +## sharing.stopSharing + +stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void + +Stops network sharing of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.stopSharing + +stopSharing(type: SharingIfaceType): Promise\ + +Stops network sharing of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.stopSharing(SharingIfaceType.SHARING_WIFI).then(() => { + console.log("stop wifi sharing successful"); +}).catch(error => { + console.log("stop wifi sharing failed"); +}); +``` + +## sharing.getStatsRxBytes + +getStatsRxBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic received via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsRxBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsRxBytes + +getStatsRxBytes(): Promise\ + +Obtains the volume of mobile data traffic received via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsRxBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getStatsTxBytes + +getStatsTxBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTxBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsTxBytes + +getStatsTxBytes(): Promise\ + +Obtains the volume of mobile data traffic sent via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTxBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getStatsTotalBytes + +getStatsTotalBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent and received via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsTotalBytes + +getStatsTotalBytes(): Promise\ + +Obtains the volume of mobile data traffic sent and received via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTotalBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharingIfaces + +getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\>): void + +Obtains the names of NICs in the specified network sharing state. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of NIC names.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharingIfaces + +getSharingIfaces(state: SharingIfaceState): Promise\> + +Obtains the names of NICs in the specified network sharing state. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return an array of NIC names.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharingState + +getSharingState(type: SharingIfaceType, callback: AsyncCallback\): void + +Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharingState + +getSharingState(type: SharingIfaceType): Promise\ + +Obtains the network sharing state of the specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[SharingIfaceState](#sharingifacestate)> | Promise used to return the network sharing state.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceType.SHARING_WIFI).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharableRegexes + +getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\>): void + +Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of regular expressions.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharableRegexes + +getSharableRegexes(type: SharingIfaceType): Promise\> + +Obtains regular expressions of NICs of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return an array of regular expressions.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## on('sharingStateChange') + +on(type: 'sharingStateChange', callback: Callback\): void + +Subscribes to network sharing state changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | Yes | Callback used to return the network sharing state.| + +**Example** + +```js +sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('sharingStateChange') + +off(type: 'sharingStateChange', callback?: Callback\): void + +Unsubscribes from network sharing state changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## on('interfaceSharingStateChange') + +on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void + +Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.| + +**Example** + +```js +sharing.on('interfaceSharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('interfaceSharingStateChange') + +off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void + +Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | No | Event name.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('interfaceSharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## on('sharingUpstreamChange') + +on(type: 'sharingUpstreamChange', callback: Callback\): void + +Subscribes to upstream network changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | Yes | Callback invoked when the upstream network changes.| + +**Example** + +```js +sharing.on('sharingUpstreamChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('sharingUpstreamChange') + +off(type: 'sharingUpstreamChange', callback?: Callback\): void + +Unsubscribes from upstream network changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('sharingUpstreamChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## SharingIfaceState + +Enumerates the network sharing states of an NIC. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| SHARING_NIC_SERVING | 1 | Network sharing is in progress.| +| SHARING_NIC_CAN_SERVER | 2 | Network sharing is supported.| +| SHARING_NIC_ERROR | 3 | An error occurred during network sharing.| + +## SharingIfaceType + +Enumerates the network sharing types of an NIC. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| +| SHARING_USB | 1 | USB sharing.| +| SHARING_BLUETOOTH | 2 | Bluetooth sharing.| diff --git a/en/application-dev/reference/apis/js-apis-net-statistics.md b/en/application-dev/reference/apis/js-apis-net-statistics.md new file mode 100644 index 0000000000000000000000000000000000000000..37d470deb661f185c4d87aa0259d67f38324651e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-statistics.md @@ -0,0 +1,409 @@ +# Network Traffic Management + +The Network Traffic Management module collects statistics on the mobile data traffic and allows you to query the data volume by network interface (cellular or Wi-Fi) or application. + +> **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. + +## Modules to Import + +```js +import statistics from '@ohos.net.statistics' +``` + +## statistics.getIfaceRxBytes + +getIfaceRxBytes(nic: string, callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic received by a specified NIC. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceRxBytes(this.nic, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceRxBytes + +getIfaceRxBytes(nic: string): Promise\; + +Obtains the volume of mobile data traffic received by a specified NIC. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceRxBytes(this.nic).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceTxBytes + +getIfaceTxBytes(nic: string, callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent by a specified NIC. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceTxBytes(this.nic, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceTxBytes + +getIfaceTxBytes(nic: string): Promise\; + +Obtains the volume of mobile data traffic sent by a specified NIC. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceTxBytes(this.nic).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularRxBytes + +getCellularRxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by the cellular network. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularRxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularRxBytes + +getCellularRxBytes(): Promise\; + +Obtains the volume of mobile data traffic received by the cellular network. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularRxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularTxBytes + +getCellularTxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by the cellular network. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularTxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularTxBytes + +getCellularTxBytes(): Promise\; + +Obtains the volume of mobile data traffic sent by the cellular network. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularTxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllRxBytes + +getAllRxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by all NICs. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllRxBytes(err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllRxBytes + +getAllRxBytes(): Promise\; + +Obtains the volume of mobile data traffic received by all NICs. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllRxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllTxBytes + +getAllTxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by all NICs. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllTxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllTxBytes + +getAllTxBytes(): Promise\; + +Obtains the volume of mobile data traffic sent by all NICs. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllTxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidRxBytes + +getUidRxBytes(uid: number, callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidRxBytes(this.uid, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidRxBytes + +getUidRxBytes(uid: number): Promise\; + +Obtains the volume of mobile data traffic received by a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidRxBytes(this.uid).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidTxBytes + +getUidTxBytes(uid: number, callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidTxBytes(this.uid, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidTxBytes + +getUidTxBytes(uid: number): Promise\; + +Obtains the volume of mobile data traffic sent by a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidTxBytes(this.uid).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index c8a9d7cf699963e494c5f04c1d5e887e8795eb0f..105af3cf95ca3a052faddbb6fe632940169fbcd1 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -1,6 +1,6 @@ # Standard NFC -The **nfcController** module implements Near-Field Communication (NFC). +The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,12 +12,24 @@ The **nfcController** module implements Near-Field Communication (NFC). import controller from '@ohos.nfc.controller'; ``` +## NfcState + +Enumerates the NFC states. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| STATE_OFF | 1 | NFC is closed (OFF).| +| STATE_TURNING_ON | 2 | NFC is turning on.| +| STATE_ON | 3 | NFC is open (ON).| +| STATE_TURNING_OFF | 4 | NFC is turning off.| ## controller.isNfcAvailable isNfcAvailable(): boolean -Checks whether NFC is available. +Checks whether the device supports NFC. **System capability**: SystemCapability.Communication.NFC.Core @@ -25,7 +37,7 @@ Checks whether NFC is available. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if NFC is available; returns **false** otherwise.| +| boolean | Returns **true** if the device supports NFC; returns **false** otherwise.| ## controller.openNfc @@ -42,7 +54,7 @@ Opens NFC. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## controller.closeNfc @@ -76,7 +88,7 @@ Checks whether NFC is open. ## controller.getNfcState -getNfcState(): NfcState +getNfcState(): [NfcState](#nfcstate) Obtains the NFC state. @@ -86,13 +98,13 @@ Obtains the NFC state. | **Type**| **Description** | | -------- | ---------------------- | -| NfcState | NFC state obtained. For details, see [NfcState](#nfcstate).| +| [NfcState](#nfcstate) | NFC state obtained. For details, see [NfcState](#nfcstate).| ## controller.on('nfcStateChange') -on(type: "nfcStateChange", callback: Callback<NfcState>): void +on(type: "nfcStateChange", callback: Callback<[NfcState](#nfcstate)>): void -Subscribes to NFC state changes. +Subscribes to NFC state changes. A callback will be invoked to return the NFC state when the NFC state changes. **System capability**: SystemCapability.Communication.NFC.Core @@ -101,15 +113,15 @@ Subscribes to NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| - | callback | Callback<NfcState> | Yes| Callback invoked to return the NFC state changes.| + | callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| ## controller.off('nfcStateChange') -off(type: "nfcStateChange", callback?: Callback<NfcState>): void +off(type: "nfcStateChange", callback?: Callback<[NfcState](#nfcstate)>): void -Unsubscribes from the NFC state changes. +Unsubscribes from the NFC state changes. The subscriber will not receive NFC state change notifications. **System capability**: SystemCapability.Communication.NFC.Core @@ -118,35 +130,37 @@ Unsubscribes from the NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| -| callback | Callback<NfcState> | No| Callback used to return the NFC state changes. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[NfcState](#nfcstate)> | No| Callback for the NFC state changes. This parameter can be left blank.| **Example** ```js - import nfcController from '@ohos.nfcController'; - - var NFC_STATE_NOTIFY = "nfcStateChange"; - - var recvNfcStateNotifyFunc = result => { - console.info("nfc state receive state: " + result); + import controller from '@ohos.nfc.controller'; + + // Define a callback key. + var NFC_STATE_CALLBACK_KEY = "nfcStateChange"; + + // Register the callback to receive NFC state change notifications. + controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> { + if (err) { + console.log("controller on callback err: " + err); + } else { + console.log("controller on callback nfcState: " + nfcState); + } + }); + + // Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (!controller.isNfcOpen()) { + var ret = controller.openNfc(); + console.log("controller openNfc ret: " + ret); } - - // Subscribe to the NFC state changes. - nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - - // Unsubscribe from the NFC state changes. - nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - ``` - -## NfcState - -Enumerates the NFC states. -**System capability**: SystemCapability.Communication.NFC.Core + // Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (controller.isNfcOpen()) { + var ret = controller.closeNfc(); + console.log("controller closeNfc ret: " + ret); + } -| Name| Default Value| Description| -| -------- | -------- | -------- | -| STATE_OFF | 1 | Off| -| STATE_TURNING_ON | 2 | Turning on| -| STATE_ON | 3 | On| -| STATE_TURNING_OFF | 4 | Turning off| + // Unregister the callback. + controller.off(NFC_STATE_CALLBACK_KEY); + ``` diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 5941d465a085a425ef7d10cb28d5fe4b621bc0b2..2f3a208fe1f95b2c4f936709d047fa4c9581f8b6 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,19 +1,100 @@ # NFC Tags -The **nfcTag** module provides methods for managing Near-Field Communication (NFC) tags. +The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. > **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. +## **Declaration** + +Before developing applications related to tag read and write, you must declare NFC-related attributes in the attribute configuration file of the applications. For example, declare the following attributes in the **module.json5** file: +```js +{ + "module": { + // Attributes to declare. + + "abilities": [ + { + "skills": [ + { + "actions": [ + // Actions to declare. + + // Add the nfc tag action. + "ohos.nfc.tag.action.TAG_FOUND" + ] + } + ], + "metadata": [ + { + "name": "tag-tech", + "value": "NfcA" + }, + { + "name": "tag-tech", + "value": "IsoDep" + }, + // Add other technologies, + // such as NfcB, NfcF, NfcV, Ndef, MifareClassic, MifareUL, and NdefFormatable. + ] + } + ], + "requestPermissions": [ + "name": "ohos.permission.NFC_TAG", + "reason": "tag", + ] + } +} +``` +> **CAUTION**
+> +> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. +> - The **name** field of **metadata** is mandatory. It must be **tag-tech** and cannot be changed. +> - The **value** field of **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or their combinations. Incorrect setting of this field will cause a parsing failure. +> - The **name** field of **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. + + ## **Modules to Import** ```js import tag from '@ohos.nfc.tag'; ``` +## **tag.TagInfo** +Before reading or writing data to a card with tags, the application must obtain **TagInfo** to determine the tag technologies supported by the card. Then, the application can invoke the correct API to communicate with the card. +```js +import tag from '@ohos.nfc.tag'; + +onCreate(want, launchParam) { + // Add other code here. + + // want is initialized by the NFC service and contains taginfo. + var tagInfo = tag.getTagInfo(want); + if (tagInfo == undefined) { + console.log("no TagInfo to be created, ignore it."); + return; + } + var isNfcATag = false; + for (var i = 0; i < tagInfo.technology.length; i++) { + if (tagInfo.technology[i] == tag.NFC_A) { + isNfcATag = true; + break; + } + // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. + } + if (isNfcATag) { + var nfcA = tag.getNfcATag(taginfo); + // Other code to read or write this tag. + } + + // use the same code to handle "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as, + // var isoDep = tag.getIsoDepTag(taginfo); +} +``` + ## tag.getNfcATag -getNfcATag(tagInfo: [TagInfo](#taginfo9)): [NfcATag](js-apis-nfctech.md#nfcatag) +getNfcATag(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag) Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. @@ -29,7 +110,7 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC- ## tag.getNfcBTag -getNfcBTag(tagInfo: [TagInfo](#taginfo9)): [NfcBTag](js-apis-nfctech.md#nfcbtag) +getNfcBTag(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag) Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. @@ -45,7 +126,7 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC- ## tag.getNfcFTag -getNfcFTag(tagInfo: [TagInfo](#taginfo9)): [NfcFTag](js-apis-nfctech.md#nfcftag) +getNfcFTag(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag) Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. @@ -61,7 +142,7 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC- ## tag.getNfcVTag -getNfcVTag(tagInfo: [TagInfo](#taginfo9)): [NfcVTag](js-apis-nfctech.md#nfcvtag) +getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. @@ -77,11 +158,10 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- ## tag.getIsoDepTag9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo9)): [IsoDepTag](js-apis-nfctech.md#isodeptag9 ) +getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology. - **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core @@ -94,7 +174,7 @@ Obtains an **IsoDepTag** object, which allows access to the tags that use the IS ## tag.getNdefTag9+ -getNdefTag(tagInfo: [TagInfo](#taginfo9)): [NdefTag](js-apis-nfctech.md#ndeftag9) +getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). @@ -111,7 +191,7 @@ Obtains an **NdefTag** object, which allows access to the tags in the NFC Data E ## tag.getMifareClassicTag9+ -getMifareClassicTag(tagInfo: [TagInfo](#taginfo9)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. @@ -127,7 +207,7 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use ## tag.getMifareUltralightTag9+ -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo9)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. @@ -143,7 +223,7 @@ Obtains a **MifareUltralightTag** object, which allows access to the tags that u ## tag.getNdefFormatableTag9+ -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo9)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. @@ -157,15 +237,143 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar | ------------------ | --------------------------| | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.| -## TagInfo9+ +## tag.getTagInfo9+ + +getTagInfo(want: Want): [TagInfo](#taginfo) + +Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [TagInfo](#taginfo) | **TagInfo** object obtained.| + +## TagInfo + +Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. -Represents the NFC tag information. +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core | **Name**| **Type**| **Description**| | -------- | -------- | -------- | -| uid | string | UID of the tag.| -| technology | number[] | Technology supported by the tag.| -| extrasData | PacMap[] | Additional information about the tag.| -| tagRfDiscId | number | RF discovery ID of the tag.| -| remoteTagService | rpc.RemoteObject | RPC remote object of the tag service.| -| supportedProfiles | number[] | Profiles supported by the tag.| +| uid9+ | number[] | Tag unique identifier (UID). Each number of the UID is a hexadecimal number ranging from **0x00** to **0xFF**.| +| technology9+ | number[] | Supported technologies. Each number is a constant indicating the supported technology.| +| supportedProfiles | number[] | Supported technologies. This parameter is not supported since API version 9 and is replaced by **technology**.| + +## NdefRecord9+ +Defines an NDEF tag record. For details, see *NFCForum-TS-NDEF_1.0*. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| tnf | number | Type name field (TNF) of an NDEF record.| +| rtdType| number[] | Record type definition (RTD) of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| +| id | number[] | ID of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| +| payload | number[] | Payload of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| + +## Technology Type Definition +Enumerates the tag technology types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| NFC_A | 1 | NFC-A (ISO 14443-3A).| +| NFC_B | 2 | NFC-A (ISO 14443-3B).| +| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| +| NFC_F | 4 | NFC-F (JIS 6319-4).| +| NFC_V | 5 | NFC-V (ISO 15693).| +| NDEF | 6 | NDEF.| +| MIFARE_CLASSIC | 8 | MIFARE Classic.| +| MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.| +| NDEF_FORMATABLE9+ | 10 | NDEF formattable.| + +## TnfType9+ +Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TNF_EMPTY | 0x0 | Empty.| +| TNF_WELL_KNOWN | 0x01 | NFC Forum Well Known Type [NFC RTD].| +| TNF_MEDIA | 0x02 | Media-type as defined in RFC 2046 [RFC 2046].| +| TNF_ABSOLUTE_URI | 0x03 | Absolute URI as defined in RFC 3986 [RFC 3986].| +| TNF_EXT_APP | 0x04 | NFC Forum external type [NFC RTD].| +| TNF_UNKNOWN | 0x05 | Unknown.| +| TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3).| + +## NDEF Record RTD +Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| RTD_TEXT9+ | [0x54] | NDEF record of the text type.| +| RTD_URI9+ | [0x55] | NDEF record of the URI type.| + +## NfcForumType9+ +Enumerates the NFC Forum tag types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.| +| NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.| +| NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.| +| NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.| +| MIFARE_CLASSIC | 101 | MIFARE Classic type.| + +## MifareClassicType9+ +Enumerates the MIFARE Classic tag types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKNOWN | -1 | Unknown type.| +| TYPE_CLASSIC | 0 | MIFARE Classic.| +| TYPE_PLUS | 1 | MIFARE Plus.| +| TYPE_PRO | 2 | MIFARE Pro.| + +## MifareClassicSize9+ +Enumerates the storage sizes of MIFARE Classic tags. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| +| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.| +| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| +| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| + +### MifareUltralightType9+ +Enumerates the MIFARE Ultralight tag types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKOWN | -1 | Unknown type.| +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| +| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| + diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md index d471510aeec29a3fce389284a54866a55b1ca507..9817e5fd5c1f2a7f797f2c20fa7b6eff18dc25a5 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -33,16 +33,17 @@ Obtains the SAK value of this NFC-A tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | SAK value obtained.| +| number | SAK value obtained. The SAK is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let sak = tag.getNfcATag(taginfo).getSak(); -console.log("sak:" +sak); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. + +let sak = nfcA.getSak(); +console.log("nfcA sak: " + sak); ``` ### NfcATag.getAtqa @@ -59,16 +60,16 @@ Obtains the ATQA value of this NFC-A tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | ATQA value obtained.| +| number[] | ATQA value obtained. Each number of the ATQA is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let atqa = tag.getNfcATag(taginfo).getAtqa(); -console.log("atqa:" +atqa); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. +let atqa = nfcA.getAtqa(); +console.log("nfcA atqa: " + atqa); ``` ## NfcBTag @@ -93,16 +94,16 @@ Obtains the application data of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Application data obtained.| +| number[] | Application data obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let appData = tag.getNfcBTag(taginfo).getRespAppData(); -console.log("appData:" +appData); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +let respAppData = nfcB.getRespAppData(); +console.log("nfcB respAppData: " + respAppData); ``` ### NfcBTag.getRespProtocol @@ -119,16 +120,16 @@ Obtains the protocol information of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Protocol information obtained.| +| number[] | Protocol information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let protocol = tag.getNfcBTag(taginfo).getRespProtocol(); -console.log("appData:" +protocol); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +let respProtocol = nfcB.getRespProtocol(); +console.log("nfcB respProtocol: " + respProtocol); ``` ## NfcFTag @@ -153,16 +154,16 @@ Obtains the system code from this NFC-F tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | System code obtained.| +| number[] | System code obtained. Each number in the system code is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let systemCode = tag.getNfcFTag(taginfo).getSystemCode(); -console.log("systemCode:" +systemCode); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +let systemCode = nfcF.getSystemCode(); +console.log("nfcF systemCode: " + systemCode); ``` ### NfcFTag.getPmm @@ -179,16 +180,16 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | PMm information obtained.| +| number[] | PMm information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let pmm = tag.getNfcFTag(taginfo).getPmm(); -console.log("pmm:" +pmm); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +let pmm = nfcF.getPmm(); +console.log("nfcF pmm: " + pmm); ``` ## NfcVTag @@ -213,16 +214,16 @@ Obtains the response flags from this NFC-V tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | Response flags obtained.| +| number | Response flags obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let flags = tag.getNfcVTag(taginfo).getResponseFlags(); -console.log("flags:" +flags); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +let responseFlags = nfcV.getResponseFlags(); +console.log("nfcV responseFlags: " + responseFlags); ``` ### NfcvTag.getDsfId @@ -239,16 +240,16 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | DSFID obtained.| +| number | DSFID obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let dsfId = tag.getNfcVTag(taginfo).getDsfId(); -console.log("dsfId:" +dsfId); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +let dsfId = nfcV.getDsfId(); +console.log("nfcV dsfId: " + dsfId); ``` ## IsoDepTag9+ @@ -261,7 +262,7 @@ The following describes the unique interfaces of **IsoDepTag**. ### IsoDepTag.getHistoricalBytes9+ -getHistoricalBytes(): string +getHistoricalBytes(): number[] Obtains the historical bytes of this tag. @@ -273,21 +274,21 @@ Obtains the historical bytes of this tag. | **Type**| **Description** | | ------------------ | --------------------------| -| string | Historical bytes obtained.| +| number[] | Historical bytes obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let historicalBytes = tag.getIsoDepTag(taginfo).getHistoricalBytes(); -console.log("historicalBytes:" +historicalBytes); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +let historicalBytes = isoDep.getHistoricalBytes(); +console.log("isoDep historicalBytes: " + historicalBytes); ``` ### IsoDepTag.getHiLayerResponse9+ -getHiLayerResponse(): string +getHiLayerResponse(): number[] Obtains the HiLayer response of this tag. @@ -299,16 +300,16 @@ Obtains the HiLayer response of this tag. | **Type**| **Description** | | ------------------ | --------------------------| -| string | HiLayer response obtained.| +| number[] | HiLayer response obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let hiLayerResponse = tag.getIsoDepTag(taginfo).getHiLayerResponse(); -console.log("hiLayerResponse:" +hiLayerResponse); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +let hiLayerResponse = isoDep.getHiLayerResponse(); +console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -332,10 +333,13 @@ Checks whether an extended application protocol data unit (APDU) is supported. T ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.getIsoDepTag(taginfo).isExtendedApduSupported().then(function (has) { - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +isoDep.isExtendedApduSupported() + .then((data) => { + console.log("isoDep isExtendedApduSupported data: " + data); + }).catch((err)=> { + console.log("isoDep isExtendedApduSupported err: " + err); + }); ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -357,11 +361,14 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.getIsoDepTag(taginfo).isExtendedApduSupported(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +isoDep.isExtendedApduSupported((err, data)=> { + if (err) { + console.log("isoDep isExtendedApduSupported err: " + err); + } else { + console.log("isoDep isExtendedApduSupported data: " + data); + } +}); ``` ## NdefTag9+ @@ -374,7 +381,7 @@ The following describes the unique interfaces of **NdefTag**. ### NdefTag.createNdefMessage9+ -createNdefMessage(data: string): [NdefMessage](#ndefmessage9) +createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) Creates an NDEF message using raw bytes. @@ -386,28 +393,30 @@ Creates an NDEF message using raw bytes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| data | string | Yes| Raw bytes of the string type.| +| data | number[] | Yes| Raw bytes used to create the message. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(data); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct. +let ndefMessage = ndef.createNdefMessage(rawData); +console.log("ndef ndefMessage: " + ndefMessage); ``` ## NdefMessage9+ ### NdefMessage.getNdefRecords9+ -getNdefRecords(): [NdefRecord](#ndefrecord9)[ ] +getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] Obtains all NDEF records. @@ -419,33 +428,18 @@ Obtains all NDEF records. | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefRecord](#ndefrecord9)[ ] | All records obtained.| +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefRecord = tag.NdefTag(taginfo).getNdefRecords(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefRecords = ndef.getNdefRecords(); +console.log("ndef ndefRecords number: " + ndefRecords.length); ``` -## NdefRecord9+ - -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| tnf | number | UID of the tag.| -| [rtdType](#rtdtype9) | string | NFC Record Type Definition (RTD) supported by the tag.| -| id | string | Additional information about the tag.| -| payload | string | RF discovery ID of the tag.| - -## RtdType9+ - -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| RTD_TEXT | 'T' | Text information.| -| RTD_URI | 'U' | Network address, email, or phone number.| - ### NdefTag.createNdefMessage9+ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) @@ -459,21 +453,32 @@ Creates an NDEF message using the NDEF records. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| ndefRecords | [NdefRecord](#ndefrecord9)[] | Yes| A list of NDEF records.| +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF records used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(ndefRecords); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefRecords = [ + // record format: tnf, rtdType, id, payload + // 1st record: + {tnf: 0x01, rtdType: [0x54], id: [0x01, 0x02, ...], payload: [0x00, 0xa4, 0x04, ...]}, + + // 2nd record: + {tnf: 0x02, rtdType: [0x55], id: [0x03, 0x04, ...], payload: [0x00, 0xa4, 0x04, ...]}, + + // other record if has one ... +]; +let ndefMessage = ndef.createNdefMessage(ndefRecords); +console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.getNdefTagType9+ @@ -490,22 +495,23 @@ Obtains the type of this NDEF tag. | **Type**| **Description** | | ------------------ | --------------------------| -| [NfcForumType](#nfcforumtype9) | NDEF tag type obtained.| +| [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NfcForumType = tag.NdefTag(taginfo).getNdefTagType(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefTagType = ndef.getNdefTagType(); +console.log("ndef ndefTagType: " + ndefTagType); ``` ### NdefTag.getNdefMessage9+ getNdefMessage(): NdefMessage -Obtains the NDEF message from the tag discovered. +Obtains the NDEF message. **Required permissions**: ohos.permission.NFC_TAG @@ -515,15 +521,16 @@ Obtains the NDEF message from the tag discovered. | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created.| +| [NdefMessage](#ndefmessage9) | NDEF message obtained. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefMessage = tag.NdefTag(taginfo).getNdefMessage(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefMessage = ndef.getNdefMessage(); +console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ @@ -547,10 +554,13 @@ Checks whether the NDEF tag is writable. This API uses a promise to return the r ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).isNdefWritable().then(function (has) { - console.log(JSON.stringify(has)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.isNdefWritable() + .then((data) => { + console.log("ndef isNdefWritable data: " + data); + }).catch((err)=> { + console.log("ndef isNdefWritable err: " + err); + }); ``` ### NdefTag.isNdefWritable9+ @@ -574,11 +584,14 @@ Checks whether the NDEF tag is writable. This API uses an asynchronous callback ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).isNdefWritable(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.isNdefWritable((err, data)=> { + if (err) { + console.log("ndef isNdefWritable err: " + err); + } else { + console.log("ndef isNdefWritable data: " + data); + } +}); ``` ### NdefTag.readNdef9+ @@ -595,17 +608,20 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the NDEF message read.| +| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).readNdef().then(function (ndefMessage) { - console.log(JSON.stringify(ndefMessage)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.readNdef() + .then((data) => { + console.log("ndef readNdef data: " + data); + }).catch((err)=> { + console.log("ndef readNdef err: " + err); + }); ``` ### NdefTag.readNdef9+ @@ -629,11 +645,14 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).readNdef(function (error, ndefMessage) { - console.log(JSON.stringify(error)) - console.log('ndefMessage: ' + ndefMessage) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.readNdef((err, data)=> { + if (err) { + console.log("ndef readNdef err: " + err); + } else { + console.log("ndef readNdef data: " + data); + } +}); ``` ### NdefTag.writeNdef9+ @@ -663,10 +682,15 @@ Writes an NDEF message to this tag. This API uses a promise to return the result ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -NdefTag.writeNdef(msg).then(function (netHandle) { - console.log(JSON.stringify(netHandle)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. + +ndef.writeNdef(ndefMessage) + .then((data) => { + console.log("ndef writeNdef data: " + data); + }).catch((err)=> { + console.log("ndef writeNdef err: " + err); + }); ``` ### NdefTag.writeNdef9+ @@ -691,18 +715,22 @@ Writes an NDEF message to this tag. This API uses an asynchronous callback to re ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).write(msg, function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. +ndef.writeNdef(ndefMessage, (err, data)=> { + if (err) { + console.log("ndef writeNdef err: " + err); + } else { + console.log("ndef writeNdef data: " + data); + } +}); ``` ### NdefTag.canSetReadOnly9+ -canSetReadOnly(): Promise\ +canSetReadOnly(): boolean -Checks whether this NDEF tag can be set to read-only. This API uses a promise to return the result. +Checks whether this NDEF tag can be set to read-only. **Required permissions**: ohos.permission.NFC_TAG @@ -712,45 +740,16 @@ Checks whether this NDEF tag can be set to read-only. This API uses a promise to | **Type**| **Description** | | ------------------ | --------------------------| -| Promise<boolean> | Promise used to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| +| boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).canSetReadOnly().then(function (has) { - console.log(JSON.stringify(has)) -}) -``` - -### NdefTag.canSetReadOnly9+ - -canSetReadOnly(callback: AsyncCallback<boolean>): void; - -Checks whether this NDEF tag can be set to read-only. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| - -**Example** - -```js -import tag from '@ohos.nfc.tag'; - -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).canSetReadOnly(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +var canSetReadOnly = ndef.canSetReadOnly(); +console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ @@ -774,15 +773,18 @@ Sets this NDEF tag to read-only. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).setReadOnly().then(function (errcode) { - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.setReadOnly() + .then((data) => { + console.log("ndef setReadOnly data: " + data); + }).catch((err)=> { + console.log("ndef setReadOnly err: " + err); + }); ``` ### NdefTag.setReadOnly9+ -setReadOnly(callback: AsyncCallback): void +setReadOnly(callback: AsyncCallback\): void Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. @@ -801,18 +803,21 @@ Sets this NDEF tag to read-only. This API uses an asynchronous callback to retur ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).setReadOnly(function (error, errcode) { - console.log(JSON.stringify(error)) - console.log('has: ' + errcode) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.setReadOnly((err, data)=> { + if (err) { + console.log("ndef setReadOnly err: " + err); + } else { + console.log("ndef setReadOnly data: " + data); + } +}); ``` ### NdefTag.getNdefTagTypeString9+ -getNdefTagTypeString(type: [NfcForumType](#nfcforumtype9)): string +getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -Converts an NFC Forum Type to a byte array defined in the NFC Forum. +Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. **Required permissions**: ohos.permission.NFC_TAG @@ -822,7 +827,7 @@ Converts an NFC Forum Type to a byte array defined in the NFC Forum. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| type | [NfcForumType](#nfcforumtype9) | Yes | NFC Forum Type.| +| type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| **Return value** @@ -835,21 +840,12 @@ Converts an NFC Forum Type to a byte array defined in the NFC Forum. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let ndefTypeString= tag.NdefTag(taginfo).getNdefTagTypeString(type); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); +console.log("ndef ndefTypeString: " + ndefTypeString); ``` -## NfcForumType9+ - -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| NFC_FORUM_TYPE_1 | 1 | NFC Forum Type 1.| -| NFC_FORUM_TYPE_2 | 2 | NFC Forum Type 2.| -| NFC_FORUM_TYPE_3 | 3 | NFC Forum Type 3.| -| NFC_FORUM_TYPE_4 | 4 | NFC Forum Type 4.| -| MIFARE_CLASSIC | 101 | MIFARE Classic.| - -## MifareClassicTag 9+ +## MifareClassicTag9+ Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**. @@ -886,15 +882,20 @@ Authenticates a sector using the key. The sector can be accessed only after the ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key).then(function (isKeyA) { - console.log(JSON.stringify(isKeyA)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorIndex = 1; // change it to be correct index. +let key = [0x04, 0x05, ....]; // change it to be correct key. +mifareClassic.authenticateSector(sectorIndex, key, true); + .then((data) => { + console.log("mifareClassic authenticateSector data: " + data); + }).catch((err)=> { + console.log("mifareClassic authenticateSector err: " + err); + }); ``` ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback): void +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. @@ -916,16 +917,21 @@ Authenticates a sector using the key. The sector can be accessed only after the ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key, function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorIndex = 1; // change it to be correct index. +let key = [0x04, 0x05, ....]; // change it to be correct key. +mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { + if (err) { + console.log("mifareClassic authenticateSector err: " + err); + } else { + console.log("mifareClassic authenticateSector data: " + data); + } +}); ``` ### MifareClassicTag.readSingleBlock9+ -readSingleBlock(blockIndex: number): Promise\ +readSingleBlock(blockIndex: number): Promise\ Reads a block (16 bytes) on the tag. This API uses a promise to return the result. @@ -943,23 +949,27 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the block data read.| +| Promise\ | Promise used to return the block data read.| **Example** ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex).then(function (data){ - console.log('data: ' + data) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock err: " + err); + } else { + console.log("mifareClassic readSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.readSingleBlock9+ -readSingleBlock(blockIndex: number, callback: AsyncCallback\): void +readSingleBlock(blockIndex: number, callback: AsyncCallback\): void Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. @@ -972,24 +982,27 @@ Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | blockIndex | number | Yes | Index of the block to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| **Example** ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex, function (error, data) { - console.log(JSON.stringify(error)) - console.log('data: ' + data) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock err: " + err); + } else { + console.log("mifareClassic readSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: string): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ Writes data to a block on the tag. This API uses a promise to return the result. @@ -1002,7 +1015,7 @@ Writes data to a block on the tag. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | blockIndex | number | Yes | Index of the target block.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| **Return value** @@ -1015,16 +1028,21 @@ Writes data to a block on the tag. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let rawData = [0x0a, 0x14, ...]; // change it to be correct data. +mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { + if (err) { + console.log("mifareClassic writeSingleBlock err: " + err); + } else { + console.log("mifareClassic writeSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: string, callback: AsyncCallback\): void +writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void Writes data to a block on the tag. This API uses an asynchronous callback to return the result. @@ -1037,7 +1055,7 @@ Writes data to a block on the tag. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | blockIndex | number | Yes | Index of the target block.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** @@ -1045,12 +1063,16 @@ Writes data to a block on the tag. This API uses an asynchronous callback to ret ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let rawData = [0x0a, 0x14, ...]; // change it to be correct data. +mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { + if (err) { + console.log("mifareClassic writeSingleBlock err: " + err); + } else { + console.log("mifareClassic writeSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.incrementBlock9+ @@ -1081,10 +1103,16 @@ Increments a block with data. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic incrementBlock err: " + err); + } else { + console.log("mifareClassic incrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.incrementBlock9+ @@ -1110,11 +1138,16 @@ Increments a block with data. This API uses an asynchronous callback to return t ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic incrementBlock err: " + err); + } else { + console.log("mifareClassic incrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.decrementBlock9+ @@ -1145,10 +1178,16 @@ Decrements a block with data. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic decrementBlock err: " + err); + } else { + console.log("mifareClassic decrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.decrementBlock9+ @@ -1174,11 +1213,16 @@ Decrements a block with data. This API uses an asynchronous callback to return t ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic decrementBlock err: " + err); + } else { + console.log("mifareClassic decrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.transferToBlock9+ @@ -1209,13 +1253,18 @@ Copies data from the register to a block. This API uses a promise to return the import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).transferToBlock(blockIndex).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.transferToBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic transferToBlock err: " + err); + } else { + console.log("mifareClassic transferToBlock data: " + data); + } +}); ``` -### MifareClassicTag.transferToBlock +### MifareClassicTag.transferToBlock9+ transferToBlock(blockIndex: number, callback: AsyncCallback\): void @@ -1237,11 +1286,15 @@ Copies data from the register to a block. This API uses an asynchronous callback ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).transferToBlock(blockIndex, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.transferToBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic transferToBlock err: " + err); + } else { + console.log("mifareClassic transferToBlock data: " + data); + } +}); ``` ### MifareClassicTag.restoreFromBlock9+ @@ -1272,10 +1325,14 @@ Copies data from a block to the register. This API uses a promise to return the import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.restoreFromBlock(blockIndex) + .then((data) => { + console.log("mifareClassic restoreFromBlock data: " + data); + }).catch((err)=> { + console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + }); ``` ### MifareClassicTag.restoreFromBlock9+ @@ -1300,11 +1357,15 @@ Copies data from a block to the register. This API uses an asynchronous callback ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic restoreFromBlock err: " + err); + } else { + console.log("mifareClassic restoreFromBlock data: " + data); + } +}); ``` ### MifareClassicTag.getSectorCount9+ @@ -1328,8 +1389,9 @@ Obtains the number of sectors in this MIFARE Classic tag. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let setorCount = tag.MifareClassicTag(taginfo).getSectorCount(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorCount = mifareClassic.getSectorCount(); +console.log("mifareClassic sectorCount: " + sectorCount); ``` ### MifareClassicTag.getBlockCountInSector9+ @@ -1359,13 +1421,14 @@ Obtains the number of blocks in a sector. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let blockNumber = tag.MifareClassicTag(taginfo).getBlockCountInSector(sectorIndex); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockCountInSector = mifareClassic.getBlockCountInSector(); +console.log("mifareClassic blockCountInSector: " + blockCountInSector); ``` ### MifareClassicTag.getType9+ -getType(): [MifareClassicType](#mifareclassictype9) +getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) Obtains the type of this MIFARE Classic tag. @@ -1377,22 +1440,23 @@ Obtains the type of this MIFARE Classic tag. | **Type**| **Description** | | ------------------ | --------------------------| -| [MifareClassicType](#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| +| [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let type = tag.MifareClassicTag(taginfo).getType(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let getType = mifareClassic.getType(); +console.log("mifareClassic getType: " + getType); ``` ### MifareClassicTag.getTagSize9+ getTagSize(): number -Obtains the tag size (in bytes). For details, see [MifareTagSize](#mifaretagsize9). +Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). **Required permissions**: ohos.permission.NFC_TAG @@ -1402,35 +1466,18 @@ Obtains the tag size (in bytes). For details, see [MifareTagSize](#mifaretagsize | **Type**| **Description** | | ------------------ | --------------------------| -| number | Tag size obtained, in bytes. For details, see [MifareTagSize](#mifaretagsize9).| +| number | Tag size obtained, in bytes. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9).| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let size = tag.MifareClassicTag(taginfo).getTagSize(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let tagSize = mifareClassic.getTagSize(); +console.log("mifareClassic tagSize: " + tagSize); ``` -## MifareClassicType9+ - -| **Name**| **Value**| **Description**| -| -------- | -------- | -------- | -| TYPE_UNKNOWN | -1 | Unknown type.| -| TYPE_CLASSIC | 0 | MIFARE Classic.| -| TYPE_PLUS | 1 | MIFARE Plus.| -| TYPE_PRO | 2 | MIFARE Pro.| - -## MifareTagSize9+ - -| **Name**| **Value**| **Description**| -| -------- | -------- | -------- | -| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| -| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.| -| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| -| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| - ### MifareClassicTag.isEmulatedTag9+ isEmulatedTag(): boolean @@ -1452,8 +1499,9 @@ Checks whether the tag is an emulated tag. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isEmulated = tag.MifareClassicTag(taginfo).isEmulatedTag(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let isEmulatedTag = mifareClassic.isEmulatedTag(); +console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` ### MifareClassicTag.getBlockIndex9+ @@ -1483,8 +1531,10 @@ Obtains the first block of a sector. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let index = tag.MifareClassicTag(taginfo).getBlockIndex(sectorIndex); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorIndex = 1; // change it to be correct index. +let blockIndex = mifareClassic.getBlockIndex(sectorIndex); +console.log("mifareClassic blockIndex: " + blockIndex); ``` ### MifareClassicTag.getSectorIndex9+ @@ -1514,8 +1564,10 @@ Obtains the index of a sector that contains the specified block. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let index = tag.MifareClassicTag(taginfo).getSectorIndex(blockIndex); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let sectorIndex = mifareClassic.getSectorIndex(blockIndex); +console.log("mifareClassic sectorIndex: " + sectorIndex); ``` ## MifareUltralightTag9+ @@ -1528,7 +1580,7 @@ The following describes the unique interfaces of **MifareUltralightTag**. ### MifareUltralightTag.readMultiplePages9+ -readMultiplePages(pageIndex: number): Promise\ +readMultiplePages(pageIndex: number): Promise\ Reads multiple pages (4 bytes per page). This API uses a promise to return the result. @@ -1546,7 +1598,7 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the data read.| +| Promise\ | Promise used to return the data read.| **Example** @@ -1554,15 +1606,19 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex).then(function (data){ - console.log("data: " + data) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +mifareUltralight.readMultiplePages(pageIndex) + .then((data) => { + console.log("mifareUltralight readMultiplePages data: " + data); + }).catch((err)=> { + console.log("mifareUltralight readMultiplePages err: " + err); + }); ``` ### MifareUltralightTag.readMultiplePages9+ -readMultiplePages(pageIndex: number, callback: AsyncCallback\): void +readMultiplePages(pageIndex: number, callback: AsyncCallback\): void Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. @@ -1575,23 +1631,27 @@ Reads multiple pages (4 bytes per page). This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | pageIndex | number | Yes | Indexes of the pages to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the data read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages err: " + err); + } else { + console.log("mifareUltralight readMultiplePages data: " + data); + } +}); ``` ### MifareUltralightTag.writeSinglePages9+ -writeSinglePages(pageIndex: number, data: string): Promise\ +writeSinglePages(pageIndex: number, data: number[]): Promise\ Writes a page of data. This API uses a promise to return the result. @@ -1604,7 +1664,7 @@ Writes a page of data. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | pageIndex | number | Yes | Index of the page.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| **Return value** @@ -1617,15 +1677,20 @@ Writes a page of data. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +mifareUltralight.writeSinglePages(pageIndex, data) + .then((data) => { + console.log("mifareUltralight writeSinglePages data: " + data); + }).catch((err)=> { + console.log("mifareUltralight writeSinglePages err: " + err); + }); ``` ### MifareUltralightTag.writeSinglePages9+ -writeSinglePages(pageIndex: number, data: string, callback: AsyncCallback\): void +writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void Writes a page of data. This API uses an asynchronous callback to return the result. @@ -1638,7 +1703,7 @@ Writes a page of data. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------ | | pageIndex | number | Yes | Index of the page.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| | callback|AsyncCallback\ |Yes| Callback invoked to return the result.| **Example** @@ -1646,18 +1711,23 @@ Writes a page of data. This API uses an asynchronous callback to return the resu ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { + if (err) { + console.log("mifareUltralight writeSinglePages err: " + err); + } else { + console.log("mifareUltralight writeSinglePages data: " + data); + } +}); ``` ### MifareUltralightTag.getType9+ getType(): MifareUltralightType -Obtains the MIFARE Ultralight tag type, in bytes. +Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9). **Required permissions**: ohos.permission.NFC_TAG @@ -1667,25 +1737,18 @@ Obtains the MIFARE Ultralight tag type, in bytes. | **Type**| **Description** | | ------------------ | --------------------------| -| MifareUltralightType | Type of the MIFARE Ultralight tag. For details, see [MifareUltralightType](#mifareultralighttype9).| +| MifareUltralightType | MIFARE Ultralight tag type obtained. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let type = tag.MifareUltralightType(taginfo).getType(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let getType = mifareClassic.getType(); +console.log("mifareUltralight getType: " + getType); ``` -### MifareUltralightType9+ - -| **Name**| **Value**| **Description**| -| -------- | -------- | -------- | -| TYPE_UNKOWN | -1 | Unknown type.| -| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| -| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| - ## NdefFormatableTag9+ Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**. @@ -1721,10 +1784,18 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).format(message).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.format(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable format err: " + err); + } else { + console.log("ndefFormatable format data: " + data); + } +}); ``` ### NdefFormatableTag.format9+ @@ -1741,19 +1812,32 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.| -| callback | AsyncCallback\ |Yes|Callback invoked to return the result.| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| callback: AsyncCallback\ | Callback invoked to return the result.| + **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).format(message, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.format(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable format err: " + err); + } else { + console.log("ndefFormatable format data: " + data); + } +}); ``` ### NdefFormatableTag.formatReadOnly9+ @@ -1783,10 +1867,18 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).formatReadOnly(message).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable formatReadOnly err: " + err); + } else { + console.log("ndefFormatable formatReadOnly data: " + data); + } +}); ``` ### NdefFormatableTag.formatReadOnly9+ @@ -1803,17 +1895,30 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.| -| callback | AsyncCallback\ |Yes|Callback invoked to return the result.| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| callback: AsyncCallback\ | Callback invoked to return the result.| + **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).formatReadOnly(message, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable formatReadOnly err: " + err); + } else { + console.log("ndefFormatable formatReadOnly data: " + data); + } +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 2f6cd9a66dcd1a5dcd1d92e126461e307643814f..ff80fc8564758868ec979ff6bf033b7084fea561 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -34,7 +34,11 @@ Publishes a notification. This API uses an asynchronous callback to return the r ```js // publish callback function publishCallback(err) { - console.info("==========================>publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } // NotificationRequest object var notificationRequest = { @@ -83,7 +87,7 @@ var notificationRequest = { } } Notification.publish(notificationRequest).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -113,7 +117,11 @@ Publishes a notification. This API uses an asynchronous callback to return the r ```js // publish callback function publishCallback(err) { - console.info("==========================>publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } // ID of the user who receives the notification var userId = 1 @@ -169,7 +177,7 @@ var notificationRequest = { var userId = 1 Notification.publish(notificationRequest, userId).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -195,7 +203,11 @@ Cancels a notification with the specified ID and label. This API uses an asynchr ```js // cancel callback function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, "label", cancelCallback) ``` @@ -221,7 +233,7 @@ Cancels a notification with the specified ID and label. This API uses a promise ```js Notification.cancel(0).then(() => { - console.info("==========================>cancelCallback=======================>"); + console.info("cancel sucess"); }); ``` @@ -247,7 +259,11 @@ Cancels a notification with the specified ID. This API uses an asynchronous call ```js // cancel callback function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, cancelCallback) ``` @@ -273,7 +289,11 @@ Cancels all notifications. This API uses an asynchronous callback to return the ```js // cancel callback function cancelAllCallback(err) { - console.info("==========================>cancelAllCallback=======================>"); + if (err.code) { + console.info("cancelAll failed " + JSON.stringify(err)); + } else { + console.info("cancelAll success"); + } } Notification.cancelAll(cancelAllCallback) ``` @@ -292,7 +312,7 @@ Cancels all notifications. This API uses a promise to return the result. ```js Notification.cancelAll().then(() => { - console.info("==========================>cancelAllCallback=======================>"); + console.info("cancelAll sucess"); }); ``` @@ -322,7 +342,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ```js // addSlot callback function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } // NotificationSlot object var notificationSlot = { @@ -359,7 +383,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.addSlot(notificationSlot).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -385,7 +409,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ```js // addSlot callback function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) ``` @@ -410,7 +438,7 @@ Adds a notification slot. This API uses a promise to return the result. ```js Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -440,7 +468,11 @@ Adds multiple notification slots. This API uses an asynchronous callback to retu ```js // addSlots callback function addSlotsCallBack(err) { - console.info("==========================>addSlotsCallBack=======================>"); + if (err.code) { + console.info("addSlots failed " + JSON.stringify(err)); + } else { + console.info("addSlots success"); + } } // NotificationSlot object var notificationSlot = { @@ -485,7 +517,7 @@ var notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlots sucess"); }); ``` @@ -511,7 +543,11 @@ Obtains a notification slot of the specified type. This API uses an asynchronous ```js // getSlot callback function getSlotCallback(err,data) { - console.info("==========================>getSlotCallback=======================>"); + if (err.code) { + console.info("getSlot failed " + JSON.stringify(err)); + } else { + console.info("getSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType, getSlotCallback) @@ -544,7 +580,7 @@ Obtains a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType).then((data) => { - console.info("==========================>getSlotCallback=======================>"); + console.info("getSlot sucess, data: " + JSON.stringify(data)); }); ``` @@ -569,7 +605,11 @@ Obtains all notification slots. This API uses an asynchronous callback to return ```js // getSlots callback function getSlotsCallback(err,data) { - console.info("==========================>getSlotsCallback=======================>"); + if (err.code) { + console.info("getSlots failed " + JSON.stringify(err)); + } else { + console.info("getSlots success"); + } } Notification.getSlots(getSlotsCallback) ``` @@ -594,7 +634,7 @@ Obtains all notification slots of this application. This API uses a promise to r ```js Notification.getSlots().then((data) => { - console.info("==========================>getSlotsCallback=======================>"); + console.info("getSlots sucess, data: " + JSON.stringify(data)); }); ``` @@ -620,7 +660,11 @@ Removes a notification slot of the specified type. This API uses an asynchronous ```js // removeSlot callback function removeSlotCallback(err) { - console.info("==========================>removeSlotCallback=======================>"); + if (err.code) { + console.info("removeSlot failed " + JSON.stringify(err)); + } else { + console.info("removeSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType,removeSlotCallback) @@ -647,7 +691,7 @@ Removes a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType).then(() => { - console.info("==========================>removeSlotCallback=======================>"); + console.info("removeSlot sucess"); }); ``` @@ -671,7 +715,11 @@ Removes all notification slots. This API uses an asynchronous callback to return ```js function removeAllCallBack(err) { - console.info("================>removeAllCallBack=======================>"); + if (err.code) { + console.info("removeAllSlots failed " + JSON.stringify(err)); + } else { + console.info("removeAllSlots success"); + } } Notification.removeAllSlots(removeAllCallBack) ``` @@ -690,7 +738,7 @@ Removes all notification slots. This API uses a promise to return the result. ```js Notification.removeAllSlots().then(() => { - console.info("==========================>removeAllCallBack=======================>"); + console.info("removeAllSlots sucess"); }); ``` @@ -721,10 +769,14 @@ Subscribes to a notification with the subscription information specified. This A ```js // subscribe callback function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -760,10 +812,14 @@ Subscribes to a notification with the subscription information specified. This A ```js function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -796,13 +852,17 @@ Subscribes to a notification with the subscription information specified. This A ```js function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } var subscriber = { onConsume: onConsumeCallback }; Notification.subscribe(subscriber).then(() => { - console.info("==========================>subscribeCallback=======================>"); + console.info("subscribe sucess"); }); ``` @@ -831,13 +891,17 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu ```js function unsubscribeCallback(err) { - console.info("==========================>unsubscribeCallback=======================>"); + if (err.code) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe success"); + } } -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback } Notification.unsubscribe(subscriber, unsubscribeCallback); ``` @@ -865,14 +929,14 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Example** ```js -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback }; Notification.unsubscribe(subscriber).then(() => { - console.info("==========================>unsubscribeCallback=======================>"); + console.info("unsubscribe sucess"); }); ``` @@ -902,7 +966,11 @@ Sets whether to enable notification for a specified bundle. This API uses an asy ```js function enableNotificationCallback(err) { - console.info("==========================>enableNotificationCallback=======================>"); + if (err.code) { + console.info("enableNotification failed " + JSON.stringify(err)); + } else { + console.info("enableNotification success"); + } } var bundle = { bundle: "bundleName1", @@ -938,7 +1006,7 @@ var bundle = { bundle: "bundleName1", } Notification.enableNotification(bundle, false).then(() => { - console.info("==========================>enableNotificationCallback=======================>"); + console.info("enableNotification sucess"); }); ``` @@ -967,7 +1035,11 @@ Checks whether notification is enabled for a specified bundle. This API uses an ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } var bundle = { bundle: "bundleName1", @@ -1008,7 +1080,7 @@ var bundle = { bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1036,7 +1108,11 @@ Checks whether notification is enabled for this application. This API uses an as ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } Notification.isNotificationEnabled(isNotificationEnabledCallback); @@ -1072,7 +1148,7 @@ Checks whether notification is enabled for this application. This API uses a pro ```js Notification.isNotificationEnabled().then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1102,7 +1178,11 @@ Sets whether to enable the notification badge for a specified bundle. This API u ```js function displayBadgeCallback(err) { - console.info("==========================>displayBadgeCallback=======================>"); + if (err.code) { + console.info("displayBadge failed " + JSON.stringify(err)); + } else { + console.info("displayBadge success"); + } } var bundle = { bundle: "bundleName1", @@ -1138,7 +1218,7 @@ var bundle = { bundle: "bundleName1", } Notification.displayBadge(bundle, false).then(() => { - console.info("==========================>displayBadgeCallback=======================>"); + console.info("displayBadge sucess"); }); ``` @@ -1167,7 +1247,11 @@ Checks whether the notification badge is enabled for a specified bundle. This AP ```js function isBadgeDisplayedCallback(err, data) { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + if (err.code) { + console.info("isBadgeDisplayed failed " + JSON.stringify(err)); + } else { + console.info("isBadgeDisplayed success"); + } } var bundle = { bundle: "bundleName1", @@ -1208,7 +1292,7 @@ var bundle = { bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + console.info("isBadgeDisplayed sucess, data: " + JSON.stringify(data)); }); ``` @@ -1238,7 +1322,11 @@ Sets the notification slot for a specified bundle. This API uses an asynchronous ```js function setSlotByBundleCallback(err) { - console.info("==========================>setSlotByBundleCallback=======================>"); + if (err.code) { + console.info("setSlotByBundle failed " + JSON.stringify(err)); + } else { + console.info("setSlotByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1280,7 +1368,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.setSlotByBundle(bundle, notificationSlot).then(() => { - console.info("==========================>setSlotByBundleCallback=======================>"); + console.info("setSlotByBundle sucess"); }); ``` @@ -1309,7 +1397,11 @@ Obtains the notification slots of a specified bundle. This API uses an asynchron ```js function getSlotsByBundleCallback(err, data) { - console.info("==========================>getSlotsByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotsByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotsByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1350,7 +1442,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { - console.info("==========================>getSlotsByBundleCallback=======================>"); + console.info("getSlotsByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1379,7 +1471,11 @@ Obtains the number of notification slots of a specified bundle. This API uses an ```js function getSlotNumByBundleCallback(err, data) { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotNumByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotNumByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1420,7 +1516,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + console.info("getSlotNumByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1428,7 +1524,7 @@ Notification.getSlotNumByBundle(bundle).then((data) => { ## Notification.remove -remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\): void +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason, callback: AsyncCallback\): void Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. @@ -1441,16 +1537,21 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **Parameters** | Name | Type | Mandatory| Description | -| --------------- | ----------------------------------- | ---- | -------------------- | +| --------------- | ----------------------------------| ---- | -------------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } var bundle = { bundle: "bundleName1", @@ -1459,14 +1560,15 @@ var notificationKey = { id: 0, label: "label", } -Notification.remove(bundle, notificationKey, removeCallback); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(bundle, notificationKey, reason, removeCallback); ``` ## Notification.remove -remove(bundle: BundleOption, notificationKey: NotificationKey): Promise\ +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason): Promise\ Removes a notification for a specified bundle. This API uses a promise to return the result. @@ -1482,6 +1584,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | --------------- | --------------- | ---- | ---------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | **Example** @@ -1493,8 +1596,9 @@ var notificationKey = { id: 0, label: "label", } -Notification.remove(bundle, notificationKey).then(() => { - console.info("==========================>removeCallback=======================>"); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(bundle, notificationKey, reason).then(() => { + console.info("remove sucess"); }); ``` @@ -1502,7 +1606,7 @@ Notification.remove(bundle, notificationKey).then(() => { ## Notification.remove -remove(hashCode: string, callback: AsyncCallback\): void +remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): void Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. @@ -1517,6 +1621,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | | hashCode | string | Yes | Unique notification ID. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1525,17 +1630,21 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal var hashCode = 'hashCode' function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } - -Notification.remove(hashCode, removeCallback); +var reason = Notification.RemoveReason.CANCEL_REASON_REMOVE; +Notification.remove(hashCode, reason, removeCallback); ``` ## Notification.remove -remove(hashCode: string): Promise\ +remove(hashCode: string, reason: RemoveReason): Promise\ Removes a notification for a specified bundle. This API uses a promise to return the result. @@ -1550,14 +1659,15 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| +| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | **Example** ```js var hashCode = 'hashCode' - -Notification.remove(hashCode).then(() => { - console.info("==========================>removeCallback=======================>"); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(hashCode, reason).then(() => { + console.info("remove sucess"); }); ``` @@ -1586,7 +1696,11 @@ Removes all notifications for a specified bundle. This API uses an asynchronous ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var bundle = { bundle: "bundleName1", @@ -1618,7 +1732,11 @@ Removes all notifications. This API uses an asynchronous callback to return the ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } Notification.removeAll(removeAllCallback); @@ -1648,7 +1766,7 @@ Removes all notifications for a specified user. This API uses a promise to retur ```js Notification.removeAll().then(() => { - console.info("==========================>removeAllCallback=======================>"); + console.info("removeAll sucess"); }); ``` @@ -1675,7 +1793,11 @@ Removes all notifications for a specified user. This API uses an asynchronous ca ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1705,7 +1827,11 @@ Removes all notifications for a specified user. This API uses a promise to retur ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1736,7 +1862,11 @@ Obtains all active notifications. This API uses an asynchronous callback to retu ```js function getAllActiveNotificationsCallback(err, data) { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getAllActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getAllActiveNotifications success"); + } } Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); @@ -1766,7 +1896,7 @@ Obtains all active notifications. This API uses a promise to return the result. ```js Notification.getAllActiveNotifications().then((data) => { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + console.info("getAllActiveNotifications sucess, data: " + JSON.stringify(data)); }); ``` @@ -1790,7 +1920,11 @@ Obtains the number of active notifications. This API uses an asynchronous callba ```js function getActiveNotificationCountCallback(err, data) { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + if (err.code) { + console.info("getActiveNotificationCount failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotificationCount success"); + } } Notification.getActiveNotificationCount(getActiveNotificationCountCallback); @@ -1816,7 +1950,7 @@ Obtains the number of active notifications. This API uses a promise to return th ```js Notification.getActiveNotificationCount().then((data) => { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + console.info("getActiveNotificationCount sucess, data: " + JSON.stringify(data)); }); ``` @@ -1840,7 +1974,11 @@ Obtains active notifications of this application. This API uses an asynchronous ```js function getActiveNotificationsCallback(err, data) { - console.info("==========================>getActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotifications success"); + } } Notification.getActiveNotifications(getActiveNotificationsCallback); @@ -1866,7 +2004,7 @@ Obtains active notifications of this application. This API uses a promise to ret ```js Notification.getActiveNotifications().then((data) => { - console.info("==========================>getActiveNotificationsCallback=======================>"); + console.info("removeGroupByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1891,7 +2029,11 @@ Cancels a notification group of this application. This API uses an asynchronous ```js function cancelGroupCallback(err) { - console.info("==========================>cancelGroupCallback=======================>"); + if (err.code) { + console.info("cancelGroup failed " + JSON.stringify(err)); + } else { + console.info("cancelGroup success"); + } } var groupName = "GroupName"; @@ -1920,7 +2062,7 @@ Cancels a notification group of this application. This API uses a promise to ret ```js var groupName = "GroupName"; Notification.cancelGroup(groupName).then(() => { - console.info("==========================>cancelGroupPromise=======================>"); + console.info("cancelGroup sucess"); }); ``` @@ -1950,7 +2092,11 @@ Removes a notification group for a specified bundle. This API uses an asynchrono ```js function removeGroupByBundleCallback(err) { - console.info("==========================>removeGroupByBundleCallback=======================>"); + if (err.code) { + console.info("removeGroupByBundle failed " + JSON.stringify(err)); + } else { + console.info("removeGroupByBundle success"); + } } var bundleOption = {bundle: "Bundle"}; @@ -1986,7 +2132,7 @@ Removes a notification group for a specified bundle. This API uses a promise to var bundleOption = {bundle: "Bundle"}; var groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName).then(() => { - console.info("==========================>removeGroupByBundlePromise=======================>"); + console.info("removeGroupByBundle sucess"); }); ``` @@ -2015,7 +2161,11 @@ Sets the DND time. This API uses an asynchronous callback to return the result. ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2056,7 +2206,7 @@ var doNotDisturbDate = { end: new Date(2021, 11, 15, 18, 0) } Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2085,7 +2235,11 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2132,7 +2286,7 @@ var doNotDisturbDate = { var userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2159,7 +2313,11 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); @@ -2189,7 +2347,7 @@ Obtains the DND time. This API uses a promise to return the result. ```js Notification.getDoNotDisturbDate().then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2217,7 +2375,11 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } var userId = 1 @@ -2257,7 +2419,7 @@ Obtains the DND time of a specified user. This API uses a promise to return the var userId = 1 Notification.getDoNotDisturbDate(userId).then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2284,7 +2446,11 @@ Checks whether the DND mode is supported. This API uses an asynchronous callback ```js function supportDoNotDisturbModeCallback(err,data) { - console.info("==========================>supportDoNotDisturbModeCallback=======================>"); + if (err.code) { + console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); + } else { + console.info("supportDoNotDisturbMode success"); + } } Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); @@ -2314,7 +2480,7 @@ Checks whether the DND mode is supported. This API uses a promise to return the ```js Notification.supportDoNotDisturbMode().then((data) => { - console.info("==========================>supportDoNotDisturbModePromise=======================>"); + console.info("supportDoNotDisturbMode sucess, data: " + JSON.stringify(data)); }); ``` @@ -2340,7 +2506,11 @@ Checks whether a specified template exists. This API uses an asynchronous callba ```javascript var templateName = 'process'; function isSupportTemplateCallback(err, data) { - console.info("isSupportTemplateCallback"); + if (err.code) { + console.info("isSupportTemplate failed " + JSON.stringify(err)); + } else { + console.info("isSupportTemplate success"); + } } Notification.isSupportTemplate(templateName, isSupportTemplateCallback); @@ -2374,7 +2544,7 @@ Checks whether a specified template exists. This API uses a promise to return th var templateName = 'process'; Notification.isSupportTemplate(templateName).then((data) => { - console.info("isSupportTemplateCallback"); + console.info("isSupportTemplate success, data: " + JSON.stringify(data)); }); ``` @@ -2398,7 +2568,11 @@ Requests notification to be enabled for this application. This API uses an async ```javascript function requestEnableNotificationCallback() { - console.log('------------- requestEnabledNotification --------------'); + if (err.code) { + console.info("requestEnableNotification failed " + JSON.stringify(err)); + } else { + console.info("requestEnableNotification success"); + } }; Notification.requestEnableNotification(requestEnableNotificationCallback); @@ -2419,7 +2593,7 @@ Requests notification to be enabled for this application. This API uses a promis ```javascript Notification.requestEnableNotification() .then(() => { - console.info("requestEnableNotification "); + console.info("requestEnableNotification sucess"); }); ``` @@ -2447,7 +2621,11 @@ Sets whether this device supports distributed notifications. This API uses an as ```javascript function enabledNotificationCallback() { - console.log('----------- enableDistributed ------------'); + if (err.code) { + console.info("enableDistributed failed " + JSON.stringify(err)); + } else { + console.info("enableDistributed success"); + } }; var enable = true @@ -2482,7 +2660,7 @@ var enable = true Notification.enableDistributed(enable) .then(() => { - console.log('-------- enableDistributed ----------'); + console.info("enableDistributed sucess"); }); ``` @@ -2505,7 +2683,11 @@ Obtains whether this device supports distributed notifications. This API uses an ```javascript function isDistributedEnabledCallback() { - console.log('----------- isDistributedEnabled ------------'); + if (err.code) { + console.info("isDistributedEnabled failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabled success"); + } }; Notification.isDistributedEnabled(isDistributedEnabledCallback); @@ -2532,7 +2714,7 @@ Obtains whether this device supports distributed notifications. This API uses a ```javascript Notification.isDistributedEnabled() .then((data) => { - console.log('-------- isDistributedEnabled ----------'); + console.info("isDistributedEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -2561,7 +2743,11 @@ Sets whether an application supports distributed notifications based on the bund ```javascript function enableDistributedByBundleCallback() { - console.log('----------- enableDistributedByBundle ------------'); + if (err.code) { + console.info("enableDistributedByBundle failed " + JSON.stringify(err)); + } else { + console.info("enableDistributedByBundle success"); + } }; var bundle = { @@ -2605,7 +2791,7 @@ var enable = true Notification.enableDistributedByBundle(bundle, enable) .then(() => { - console.log('-------- enableDistributedByBundle ----------'); + console.info("enableDistributedByBundle sucess"); }); ``` @@ -2632,7 +2818,11 @@ Obtains whether an application supports distributed notifications based on the b ```javascript function isDistributedEnabledByBundleCallback(data) { - console.log('----------- isDistributedEnabledByBundle ------------', data); + if (err.code) { + console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabledByBundle success"); + } }; var bundle = { @@ -2677,7 +2867,7 @@ var bundle = { Notification.isDistributedEnabledByBundle(bundle) .then((data) => { - console.log('-------- isDistributedEnabledByBundle ----------', data); + console.info("isDistributedEnabledByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -2704,7 +2894,11 @@ Obtains the notification reminder type. This API uses an asynchronous callback t ```javascript function getDeviceRemindTypeCallback(data) { - console.log('----------- getDeviceRemindType ------------', data); + if (err.code) { + console.info("getDeviceRemindType failed " + JSON.stringify(err)); + } else { + console.info("getDeviceRemindType success"); + } }; Notification.getDeviceRemindType(getDeviceRemindTypeCallback); @@ -2735,7 +2929,7 @@ Obtains the notification reminder type. This API uses a promise to return the re ```javascript Notification.getDeviceRemindType() .then((data) => { - console.log('-------- getDeviceRemindType ----------', data); + console.info("getDeviceRemindType sucess, data: " + JSON.stringify(data)); }); ``` @@ -2766,7 +2960,11 @@ Publishes an agent-powered notification. This API uses an asynchronous callback ```js // Callback for publishAsBundle function publishAsBundleCallback(err) { - console.info("==========================>publishAsBundleCallback=======================>"); + if (err.code) { + console.info("publishAsBundle failed " + JSON.stringify(err)); + } else { + console.info("publishAsBundle success"); + } } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" @@ -2830,7 +3028,7 @@ var notificationRequest = { } Notification.publishAsBundle(notificationRequest, representativeBundle, userId).then(() => { - console.info("==========================>publishAsBundleCallback=======================>"); + console.info("publishAsBundle sucess"); }); ``` @@ -2862,7 +3060,11 @@ Cancels a notification published by the reminder agent. This API uses an asynchr ```js //cancelAsBundle function cancelAsBundleCallback(err) { - console.info("==========================>cancelAsBundleCallback=======================>"); + if (err.code) { + console.info("cancelAsBundle failed " + JSON.stringify(err)); + } else { + console.info("cancelAsBundle success"); + } } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" @@ -2903,7 +3105,7 @@ let representativeBundle = "com.example.demo" let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { - console.info("==========================>cancelAsBundleCallback=======================>"); + console.info("cancelAsBundle success"); }); ``` @@ -2933,7 +3135,11 @@ Sets the enabled status for a notification slot of a specified type. This API us ```js //enableNotificationSlot function enableSlotCallback(err) { - console.log('===================>enableSlotCallback==================>'); + if (err.code) { + console.info("enableNotificationSlot failed " + JSON.stringify(err)); + } else { + console.info("enableNotificationSlot success"); + } }; Notification.enableNotificationSlot( @@ -2971,7 +3177,7 @@ Notification.enableNotificationSlot( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION, true).then(() => { - console.log('====================>enableNotificationSlot====================>'); + console.info("enableNotificationSlot sucess"); }); ``` @@ -3000,7 +3206,11 @@ Obtains the enabled status of the notification slot of a specified type. This AP ```js //isNotificationSlotEnabled function getEnableSlotCallback(err, data) { - console.log('===================>getEnableSlotCallback=================='); + if (err.code) { + console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationSlotEnabled success"); + } }; Notification.isNotificationSlotEnabled( @@ -3042,7 +3252,7 @@ Notification.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION ).then((data) => { - console.log('====================>isNotificationSlotEnabled====================>'); + console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -3074,7 +3284,11 @@ let userId = 100; let enable = true; function setSyncNotificationEnabledWithoutAppCallback(err) { - console.log('setSyncNotificationEnabledWithoutAppCallback'); + if (err.code) { + console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); + } else { + console.info("setSyncNotificationEnabledWithoutApp success"); + } } Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotificationEnabledWithoutAppCallback); @@ -3113,11 +3327,11 @@ let userId = 100; let enable = true; Notification.setSyncNotificationEnabledWithoutApp(userId, enable) - .then((data) => { - console.log('setSyncNotificationEnabledWithoutApp'); + .then(() => { + console.info('setSyncNotificationEnabledWithoutApp'); }) .catch((err) => { - console.log('setSyncNotificationEnabledWithoutApp, err:', err); + console.info('setSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3148,9 +3362,9 @@ let userId = 100; function getSyncNotificationEnabledWithoutAppCallback(data, err) { if (err) { - console.log('getSyncNotificationEnabledWithoutAppCallback, err' + err); + console.info('getSyncNotificationEnabledWithoutAppCallback, err' + err); } else { - console.log('getSyncNotificationEnabledWithoutAppCallback, data' + data); + console.info('getSyncNotificationEnabledWithoutAppCallback, data' + data); } } @@ -3189,10 +3403,10 @@ let userId = 100; Notification.getSyncNotificationEnabledWithoutApp(userId) .then((data) => { - console.log('getSyncNotificationEnabledWithoutApp, data:', data); + console.info('getSyncNotificationEnabledWithoutApp, data:', data); }) .catch((err) => { - console.log('getSyncNotificationEnabledWithoutApp, err:', err); + console.info('getSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3236,7 +3450,7 @@ function onConsumeCallback(data) { let wantAgent = data.wantAgent; wantAgent .getWant(wantAgent) .then((data1) => { - console.log('===> getWant success want:' + JSON.stringify(data1)); + console.info('===> getWant success want:' + JSON.stringify(data1)); }) .catch((err) => { console.error('===> getWant failed because' + JSON.stringify(err)); @@ -3877,3 +4091,14 @@ Notification.subscribe(subscriber, subscribeCallback); | TYPE_NORMAL | 0 | Normal notification. | | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | + +## RemoveReason9+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | -------------------- | +| CLICK_REASON_REMOVE | 1 | The notification is removed due to a click on it. | +| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 8320fceaa5601703f01f8fc8f4937bcd34d3b4d5..36e075f0e24f3a01dfc7feddc29173c364e0b885 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,6 +1,6 @@ # OS Account Management -The **osAccount** module provides basic capabilities for managing operating system (OS) accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account, and storing OS account data to disks. +The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. > **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. @@ -22,9 +22,9 @@ Obtains an **AccountManager** instance. **Return value** -| Type | Description | -| --------------------------------- | ------------------------ | -| [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.| +| Type | Description | +| --------------------------------- | ---------------- | +| [AccountManager](#accountmanager) | **AccountManager** instance obtained.| **Example** ```js @@ -33,19 +33,19 @@ Obtains an **AccountManager** instance. ## OsAccountType -Enumerates OS account types. +Enumerates the OS account types. **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | -| ------ | ------ | ------------ | +| ------ | ------ | ----------- | | ADMIN | 0 | Administrator account| | NORMAL | 1 | Normal account | | GUEST | 2 | Guest account | ## AccountManager -Provides methods to manage OS accounts. +Provides APIs for managing OS accounts. ### activateOsAccount @@ -53,7 +53,7 @@ activateOsAccount(localId: number, callback: AsyncCallback<void>): void Activates an OS account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION @@ -61,18 +61,36 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| localId | number | Yes | ID of the OS account to activate.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | +| 12300009 | Account has been activated. | **Example**: Activate OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.activateOsAccount(localId, (err)=>{ - console.log('activateOsAccount err:' + JSON.stringify(err)); - }); + try { + accountManager.activateOsAccount(localId, (err)=>{ + if (err) { + console.log("activateOsAccount failed, error:" + JSON.stringify(err)); + } else { + console.log("activateOsAccount successfully"); + } + }); + } catch (err) { + console.log("activateOsAccount exception:" + JSON.stringify(err)); + } ``` ### activateOsAccount @@ -81,7 +99,7 @@ activateOsAccount(localId: number): Promise<void> Activates an OS account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION @@ -91,28 +109,42 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------- | -| localId | number | Yes | ID of the OS account to activate.| +| localId | number | Yes | ID of the target OS account.| **Return value** -| Type | Description | -| :------------------ | :---------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | +| 12300009 | Account has been activated. | **Example**: Activate OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.activateOsAccount(localId).then(() => { - console.log('activateOsAccount success'); - }).catch((err) => { - console.log('activateOsAccount err:' + JSON.stringify(err)); - }); + try { + accountManager.activateOsAccount(localId).then(() => { + console.log('activateOsAccount successfully'); + }).catch((err) => { + console.log('activateOsAccount failed, err:' + JSON.stringify(err)); + }); + } catch (e) { + console.log('activateOsAccount exception:' + JSON.stringify(e)); + } ``` -### isMultiOsAccountEnable +### checkMultiOsAccountEnabled9+ -isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void +checkMultiOsAccountEnabled(callback: AsyncCallback<boolean>): void Checks whether multiple OS accounts are supported. This API uses an asynchronous callback to return the result. @@ -120,23 +152,36 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | --------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If multiple OS accounts are supported, **true** will be returned. Otherwise, **false** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isMultiOsAccountEnable((err, isEnabled) => { - console.log('isMultiOsAccountEnable err: ' + JSON.stringify(err)); - console.log('isMultiOsAccountEnable isEnabled: ' + isEnabled); - }); + try { + accountManager.checkMultiOsAccountEnabled((err, isEnabled) => { + if (err) { + console.log("checkMultiOsAccountEnabled failed, error: " + JSON.stringify(err)); + } else { + console.log("checkMultiOsAccountEnabled successfully, isEnabled: " + isEnabled); + } + }); + } catch (err) { + console.log("checkMultiOsAccountEnabled exception: " + JSON.stringify(err)); + } ``` -### isMultiOsAccountEnable +### checkMultiOsAccountEnabled9+ -isMultiOsAccountEnable(): Promise<boolean> +checkMultiOsAccountEnabled(): Promise<boolean> Checks whether multiple OS accounts are supported. This API uses a promise to return the result. @@ -144,52 +189,77 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re **Return value** -| Type | Description | -| :--------------------- | :----------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If multiple OS accounts are supported, **true** will be returned. Otherwise, **false** will be returned.| +| Type | Description | +| :--------------------- | :--------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js - let accountManager = account_osAccount.getAccountManager(); - accountManager.isMultiOsAccountEnable().then((isEnabled) => { - console.log('isMultiOsAccountEnable, isEnabled: ' + isEnabled); - }).catch((err) => { - console.log('isMultiOsAccountEnable err: ' + JSON.stringify(err)); - }); + try { + let accountManager = account_osAccount.getAccountManager(); + accountManager.checkMultiOsAccountEnabled().then((isEnabled) => { + console.log('checkMultiOsAccountEnabled successfully, isEnabled: ' + isEnabled); + }).catch((err) => { + console.log('checkMultiOsAccountEnabled failed, error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('checkMultiOsAccountEnabled exception: ' + JSON.stringify(err)); + } ``` -### isOsAccountActived +### checkOsAccountActivated9+ -isOsAccountActived(localId: number, callback: AsyncCallback<boolean>): void +checkOsAccountActivated(localId: number, callback: AsyncCallback<boolean>): void Checks whether an OS account is activated. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the OS account is activated, **true** will be returned. Otherwise, **false** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------ | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Check whether OS account 100 is activated. ```js let accountManager = account_osAccount.getAccountManager(); - let osLocalId = 100; - accountManager.isOsAccountActived(osLocalId, (err, isActive)=>{ - console.log('isOsAccountActived err:' + JSON.stringify(err)); - console.log('isOsAccountActived isActive:' + isActive); - }); + let localId = 100; + try { + accountManager.checkOsAccountActivated(localId, (err, isActivated) => { + if (err) { + console.log('checkOsAccountActivated failed, error:' + JSON.stringify(err)); + } else { + console.log('checkOsAccountActivated successfully, isActivated:' + isActivated); + } + }); + } catch (err) { + console.log('checkOsAccountActivated exception:' + JSON.stringify(err)); + } ``` -### isOsAccountActived +### checkOsAccountActivated9+ -isOsAccountActived(localId: number): Promise<boolean> +checkOsAccountActivated(localId: number): Promise<boolean> Checks whether an OS account is activated. This API uses a promise to return the result. @@ -199,60 +269,88 @@ Checks whether an OS account is activated. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------ | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------- | | localId | number | Yes | ID of the target OS account.| **Return value** -| Type | Description | -| :--------------------- | :----------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If the OS account is activated, **true** will be returned. Otherwise, **false** will be returned.| +| Type | Description | +| ---------------------- | ---------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Check whether OS account 100 is activated. ```js let accountManager = account_osAccount.getAccountManager(); - let osLocalId = 100; - accountManager.isOsAccountActived(osLocalId).then((isActive) => { - console.log('isOsAccountActived, isActive: ' + isActive); - }).catch((err) => { - console.log('isOsAccountActived err: ' + JSON.stringify(err)); - }); + let localId = 100; + try { + accountManager.checkOsAccountActivated(localId).then((isActivated) => { + console.log('checkOsAccountActivated successfully, isActivated: ' + isActivated); + }).catch((err) => { + console.log('checkOsAccountActivated failed, error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('checkOsAccountActivated exception:' + JSON.stringify(err)); + } ``` -### isOsAccountConstraintEnable +### checkConstraintEnabled9+ -isOsAccountConstraintEnable(localId: number, constraint: string, callback: AsyncCallback<boolean>): void +checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback<boolean>): void Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------- | ---- | ------------------------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| constraint | string | Yes | [Constraint](#constraints) specified. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the constraint is enabled for the OS account, **true** will be returned. Otherwise, **false** will be returned.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------- | ---- | ----------------------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| constraint | string | Yes | [Constraint](#constraints) to check. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Check whether OS account 100 is forbidden to use Wi-Fi. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.isOsAccountConstraintEnable(localId, 'constraint.wifi', (err, isConstraintEnabled)=>{ - console.log('isOsAccountConstraintEnable err:' + JSON.stringify(err)); - console.log('isOsAccountConstraintEnable isConstraintEnabled:' + isConstraintEnabled); - }); + let constraint = "constraint.wifi"; + try { + accountManager.checkConstraintEnabled(localId, constraint, (err, isEnabled)=>{ + if (err) { + console.log("checkConstraintEnabled failed, error: " + JSON.stringify(err)); + } else { + console.log("checkConstraintEnabled successfully, isEnabled: " + isEnabled); + } + }); + } catch (err) { + console.log("checkConstraintEnabled exception: " + JSON.stringify(err)); + } ``` -### isOsAccountConstraintEnable +### checkConstraintEnabled9+ -isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boolean> +checkConstraintEnabled(localId: number, constraint: string): Promise<boolean> Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result. @@ -262,32 +360,45 @@ Checks whether the specified constraint is enabled for an OS account. This API u **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ------------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| constraint | string | Yes | [Constraint](#constraints) specified.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ---------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| constraint | string | Yes | [Constraint](#constraints) to check.| **Return value** -| Type | Description | -| :--------------------- | :----------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If the constraint is enabled for the OS account, **true** will be returned. Otherwise, **false** will be returned.| +| Type | Description | +| --------------------- | --------------------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Check whether OS account 100 is forbidden to use Wi-Fi. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.isOsAccountConstraintEnable(localId, 'constraint.wifi').then((isConstraintEnabled) => { - console.log('isOsAccountConstraintEnable, isConstraintEnabled: ' + isConstraintEnabled); - }).catch((err) => { - console.log('isOsAccountConstraintEnable err: ' + JSON.stringify(err)); - }); + let constraint = "constraint.wifi"; + try { + accountManager.checkConstraintEnabled(localId, constraint).then((isEnabled) => { + console.log("checkConstraintEnabled successfully, isEnabled: " + isEnabled); + }).catch((err) => { + console.log("checkConstraintEnabled failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkConstraintEnabled exception: " + JSON.stringify(err)); + } ``` -### isTestOsAccount +### checkOsAccountTestable9+ -isTestOsAccount(callback: AsyncCallback<boolean>): void +checkOsAccountTestable(callback: AsyncCallback<boolean>): void Checks whether this OS account is a test account. This API uses an asynchronous callback to return the result. @@ -295,23 +406,36 @@ Checks whether this OS account is a test account. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ----------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the account is a test account, **true** will be returned. Otherwise, **false** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | --------------------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isTestOsAccount((err, isTest) => { - console.log('isTestOsAccount err: ' + JSON.stringify(err)); - console.log('isTestOsAccount isTest: ' + isTest); - }); + try { + accountManager.checkOsAccountTestable((err, isTestable) => { + if (err) { + console.log("checkOsAccountTestable failed, error: " + JSON.stringify(err)); + } else { + console.log("checkOsAccountTestable successfully, isTestable: " + isTestable); + } + }); + } catch (err) { + console.log("checkOsAccountTestable error: " + JSON.stringify(err)); + } ``` -### isTestOsAccount +### checkOsAccountTestable9+ -isTestOsAccount(): Promise<boolean> +checkOsAccountTestable(): Promise<boolean> Checks whether this OS account is a test account. This API uses a promise to return the result. @@ -319,48 +443,75 @@ Checks whether this OS account is a test account. This API uses a promise to ret **Return value** -| Type | Description | -| :--------------------- | :----------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If the account is a test account, **true** will be returned. Otherwise, **false** will be returned.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isTestOsAccount().then((isTest) => { - console.log('isTestOsAccount, isTest: ' + isTest); - }).catch((err) => { - console.log('isTestOsAccount err: ' + JSON.stringify(err)); - }); + try { + accountManager.checkOsAccountTestable().then((isTestable) => { + console.log("checkOsAccountTestable successfully, isTestable: " + isTestable); + }).catch((err) => { + console.log("checkOsAccountTestable failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log('checkOsAccountTestable exception: ' + JSON.stringify(err)); + } ``` -### isOsAccountVerified +### checkOsAccountVerified9+ -isOsAccountVerified(callback: AsyncCallback<boolean>): void +checkOsAccountVerified(callback: AsyncCallback<boolean>): void Checks whether this OS account has been verified. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the OS account has been verified, **true** will be returned. Otherwise, **false** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isOsAccountVerified((err, isVerified) => { - console.log('isOsAccountVerified err: ' + JSON.stringify(err)); - console.log('isOsAccountVerified isVerified: ' + isVerified); - }); + try { + accountManager.checkOsAccountVerified((err, isVerified) => { + if (err) { + console.log("checkOsAccountVerified failed, error: " + JSON.stringify(err)); + } else { + console.log("checkOsAccountVerified successfully, isVerified: " + isVerified); + } + }); + } catch (err) { + console.log("checkOsAccountVerified exception: " + JSON.stringify(err)); + } ``` -### isOsAccountVerified +### checkOsAccountVerified9+ -isOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void +checkOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void Checks whether an OS account has been verified. This API uses an asynchronous callback to return the result. @@ -370,24 +521,40 @@ Checks whether an OS account has been verified. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------- | -| localId | number | No | ID of the target OS account. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the OS account has been verified, **true** will be returned. Otherwise, **false** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------- | +| localId | number | No | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isOsAccountVerified((err, isVerified) => { - console.log('isOsAccountVerified err: ' + JSON.stringify(err)); - console.log('isOsAccountVerified isVerified: ' + isVerified); - }); + let localId = 100; + try { + accountManager.checkOsAccountVerified(localId, (err, isVerified) => { + if (err) { + console.log("checkOsAccountVerified failed, error: " + JSON.stringify(err)); + } else { + console.log("checkOsAccountVerified successfully, isVerified: " + isVerified); + } + }); + } catch (err) { + console.log("checkOsAccountVerified exception: " + err); + } ``` -### isOsAccountVerified +### checkOsAccountVerified9+ -isOsAccountVerified(localId?: number): Promise<boolean> +checkOsAccountVerified(localId?: number): Promise<boolean> Checks whether an OS account has been verified. This API uses a promise to return the result. @@ -397,34 +564,47 @@ Checks whether an OS account has been verified. This API uses a promise to retur **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------ | -| localId | number | No | ID of the target OS account.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------------------------------------- | +| localId | number | No | ID of the target OS account. If this parameter is not specified, this API checks whether the current OS account has been verified.| **Return value** -| Type | Description | -| :--------------------- | :----------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If the OS account has been verified, **true** will be returned. Otherwise, **false** will be returned.| +| Type | Description | +| ---------------------- | ----------------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isOsAccountVerified().then((isVerified) => { - console.log('isOsAccountVerified, isVerified: ' + isVerified); - }).catch((err) => { - console.log('isOsAccountVerified err: ' + JSON.stringify(err)); - }); + let localId = 100; + try { + accountManager.checkOsAccountVerified(localId).then((isVerified) => { + console.log("checkOsAccountVerified successfully, isVerified: " + isVerified); + }).catch((err) => { + console.log("checkOsAccountVerified failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log('checkOsAccountVerified exception: ' + JSON.stringify(err)); + } ``` ### removeOsAccount removeOsAccount(localId: number, callback: AsyncCallback<void>): void -Removes an OS account. This API uses an asynchronous callback to return the result. +Deletes an OS account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -432,29 +612,47 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| localId | number | Yes | ID of the OS account to remove.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.createOsAccount('testAccountName', account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo) => { - accountManager.removeOsAccount(osAccountInfo.localId, (err)=>{ - console.log('removeOsAccount err:' + JSON.stringify(err)); + let accountName = "testAccountName"; + try { + accountManager.createOsAccount(accountName, account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo) => { + accountManager.removeOsAccount(osAccountInfo.localId, (err)=>{ + if (err) { + console.log("removeOsAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("removeOsAccount successfully"); + } + }); }); - }); + } catch (err) { + console.log('removeOsAccount exception:' + JSON.stringify(err)); + } ``` ### removeOsAccount removeOsAccount(localId: number): Promise<void> -Removes an OS account. This API uses a promise to return the result. +Deletes an OS account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -462,27 +660,41 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | -------------------- | -| localId | number | Yes | ID of the OS account to remove.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------- | +| localId | number | Yes | ID of the target OS account.| **Return value** -| Type | Description | -| :------------------ | :---------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.createOsAccount('testAccountName', account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ - accountManager.removeOsAccount(osAccountInfo.localId).then(() => { - console.log('removeOsAccount Success'); - }).catch(() => { - console.log('removeOsAccount err: ' + JSON.stringify(err)); + let accountName = "testAccountName"; + try { + accountManager.createOsAccount(accountName, account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + accountManager.removeOsAccount(osAccountInfo.localId).then(() => { + console.log("removeOsAccount successfully"); + }).catch((err) => { + console.log("removeOsAccount failed, error: " + JSON.stringify(err)); + }); }); - }); + } catch (err) { + console.log("removeOsAccount exception: " + JSON.stringify(err)); + } ``` ### setOsAccountConstraints @@ -491,7 +703,7 @@ setOsAccountConstraints(localId: number, constraints: Array<string>, enabl Sets or removes constraints for an OS account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -499,21 +711,39 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | -------------------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| constraints | Array<string> | Yes | List of [constraints](#constraints) to set or remove.| -| enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | ----------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| constraints | Array<string> | Yes | List of [constraints](#constraints) to set or remove. | +| enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example**: Disable Wi-Fi for OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.setOsAccountConstraints(localId, ['constraint.wifi'], true, (err)=>{ - console.log('setOsAccountConstraints err:' + JSON.stringify(err)); - }); + let constraint = "constraint.wifi"; + try { + accountManager.setOsAccountConstraints(localId, [constraint], true, (err) => { + if (err) { + console.log("setOsAccountConstraints failed, error:" + JSON.stringify(err)); + } else { + console.log("setOsAccountConstraints successfully"); + } + }); + } catch (err) { + console.log("setOsAccountConstraints exception: " + JSON.stringify(err)); + } ``` ### setOsAccountConstraints @@ -522,7 +752,7 @@ setOsAccountConstraints(localId: number, constraints: Array<string>, enabl Sets or removes constraints for an OS account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -532,26 +762,39 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ----------- | ------------------- | ---- | -------------------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| constraints | Array<string> | Yes | List of [constraints](#constraints) to set or remove.| +| localId | number | Yes | ID of the target OS account. | +| constraints | Array<string> | Yes | List of [constraints](#constraints) to set or remove. | | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | **Return value** -| Type | Description | -| :------------------ | :---------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| :------------------ | :----------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example**: Remove the constraint on the use of Wi-Fi for OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.setOsAccountConstraints(localId, ['constraint.location.set'], false).then(() => { - console.log('setOsAccountConstraints Success'); - }).catch((err) => { - console.log('setOsAccountConstraints err: ' + JSON.stringify(err)); - }); + try { + accountManager.setOsAccountConstraints(localId, ['constraint.location.set'], false).then(() => { + console.log('setOsAccountConstraints succsuccessfully'); + }).catch((err) => { + console.log('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('setOsAccountConstraints exception:' + JSON.stringify(err)); + } ``` ### setOsAccountName @@ -560,7 +803,7 @@ setOsAccountName(localId: number, localName: string, callback: AsyncCallback< Sets a name for an OS account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -568,21 +811,38 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| :-------- | ------------------------- | ---- | ------------ | -| localId | number | Yes | ID of the target OS account.| -| localName | string | Yes | Account name to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :-------- | ------------------------- | ---- | ----------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| localName | string | Yes | Account name to set. The value cannot exceed 1024 characters. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or localName. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example**: Set the name of OS account 100 to **demoName**. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - let newName = 'demoName'; - accountManager.setOsAccountName(localId, newName, (err)=>{ - console.debug('setOsAccountName err:' + JSON.stringify(err)); - }); + let name = "demoName"; + try { + accountManager.setOsAccountName(localId, name, (err) => { + if (err) { + console.log("setOsAccountName failed, error: " + JSON.stringify(err)); + } else { + console.log("setOsAccountName successfully"); + } + }); + } catch (err) { + console.log('setOsAccountName exception:' + JSON.stringify(err)); + } ``` ### setOsAccountName @@ -591,7 +851,7 @@ setOsAccountName(localId: number, localName: string): Promise<void> Sets a name for an OS account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -599,33 +859,46 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------ | +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------------------------------- | | localId | number | Yes | ID of the target OS account.| -| localName | string | Yes | Account name to set. | +| localName | string | Yes | Account name to set. The value cannot exceed 1024 characters. | **Return value** -| Type | Description | -| :------------------ | :---------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or localName. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example**: Set the name of OS account 100 to **demoName**. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - let nameLimit = 'demoName'; - accountManager.setOsAccountName(localId, nameLimit).then(() => { - console.log('setOsAccountName Success'); - }).catch((err) => { - console.log('setOsAccountName err: ' + JSON.stringify(err)); - }); + let name = 'testName'; + try { + accountManager.setOsAccountName(localId, name).then(() => { + console.log('setOsAccountName successfully'); + }).catch((err) => { + console.log('setOsAccountName failed, error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('setOsAccountName exception:' + JSON.stringify(err)); + } ``` -### getCreatedOsAccountsCount +### getOsAccountCount9+ -getCreatedOsAccountsCount(callback: AsyncCallback<number>): void +getOsAccountCount(callback: AsyncCallback<number>): void Obtains the number of OS accounts created. This API uses an asynchronous callback to return the result. @@ -635,23 +908,36 @@ Obtains the number of OS accounts created. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------ | -| callback | AsyncCallback<number> | Yes | Callback used to return the number of OS accounts created.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the number of created OS accounts. If the operation fails, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getCreatedOsAccountsCount((err, accountCnt)=>{ - console.log('obtains the number of all os accounts created err:' + JSON.stringify(err)); - console.log('obtains the number of all os accounts created accountCnt:' + accountCnt); - }); + try { + accountManager.getOsAccountCount((err, count) => { + if (err) { + console.log("getOsAccountCount failed, error: " + JSON.stringify(err)); + } else { + console.log("getOsAccountCount successfully, count: " + count); + } + }); + } catch (err) { + console.log("getOsAccountCount exception: " + JSON.stringify(err)); + } ``` -### getCreatedOsAccountsCount +### getOsAccountCount9+ -getCreatedOsAccountsCount(): Promise<number> +getOsAccountCount(): Promise<number> Obtains the number of OS accounts created. This API uses a promise to return the result. @@ -661,24 +947,34 @@ Obtains the number of OS accounts created. This API uses a promise to return the **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<number> | Promise used to return the number of OS accounts created.| +| Type | Description | +| --------------------- | -------------------------------------- | +| Promise<number> | Promise used to return the number of created OS accounts.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getCreatedOsAccountsCount().then((accountCnt) => { - console.log('getCreatedOsAccountsCount, accountCnt: ' + accountCnt); - }).catch((err) => { - console.log('getCreatedOsAccountsCount err: ' + JSON.stringify(err)); - }); + try { + accountManager.getOsAccountCount().then((count) => { + console.log("getOsAccountCount successfully, count: " + count); + }).catch((err) => { + console.log("getOsAccountCount failed, error: " + JSON.stringify(err)); + }); + } catch(err) { + console.log('getOsAccountCount exception:' + JSON.stringify(err)); + } ``` -### getOsAccountLocalIdFromProcess +### queryOsAccountLocalIdFromProcess9+ -getOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void +queryOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void Obtains the ID of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. @@ -686,23 +982,36 @@ Obtains the ID of the OS account to which the current process belongs. This API **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------------------------------------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the account ID obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------------------------------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account ID obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountLocalIdFromProcess((err, accountID) => { - console.log('getOsAccountLocalIdFromProcess err: ' + JSON.stringify(err)); - console.log('getOsAccountLocalIdFromProcess accountID: ' + accountID); - }); + try { + accountManager.queryOsAccountLocalIdFromProcess((err, localId) => { + if (err) { + console.log("queryOsAccountLocalIdFromProcess failed, error: " + JSON.stringify(err)); + } else { + console.log("queryOsAccountLocalIdFromProcess successfully, localId: " + localId); + } + }); + } catch (err) { + console.log("queryOsAccountLocalIdFromProcess exception: " + JSON.stringify(err)); + } ``` -### getOsAccountLocalIdFromProcess +### queryOsAccountLocalIdFromProcess9+ -getOsAccountLocalIdFromProcess(): Promise<number> +queryOsAccountLocalIdFromProcess(): Promise<number> Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result. @@ -710,24 +1019,34 @@ Obtains the ID of the OS account to which the current process belongs. This API **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<number> | Promise used to return the account ID obtained.| +| Type | Description | +| --------------------- | ---------------------------------------- | +| Promise<number> | Promise used to return the OS account ID obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountLocalIdFromProcess().then((accountID) => { - console.log('getOsAccountLocalIdFromProcess, accountID: ' + accountID); - }).catch((err) => { - console.log('getOsAccountLocalIdFromProcess err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryOsAccountLocalIdFromProcess().then((localId) => { + console.log("queryOsAccountLocalIdFromProcess successfully, localId: " + localId); + }).catch((err) => { + console.log("queryOsAccountLocalIdFromProcess failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log('queryOsAccountLocalIdFromProcess exception: ' + JSON.stringify(err)); + } ``` -### getOsAccountLocalIdFromUid +### queryOsAccountLocalIdFromUid9+ -getOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void +queryOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void Obtains the OS account ID based on the process UID. This API uses an asynchronous callback to return the result. @@ -735,25 +1054,38 @@ Obtains the OS account ID based on the process UID. This API uses an asynchronou **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | --------------------------------------------- | -| uid | number | Yes | Process UID. | -| callback | AsyncCallback<number> | Yes | Callback used to return the OS account ID obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------------------------- | +| uid | number | Yes | Process UID. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account ID obtained. Otherwise, **data** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid uid. | **Example**: Obtain the ID of the OS account whose process UID is **12345678**. ```js let accountManager = account_osAccount.getAccountManager(); let uid = 12345678; - accountManager.getOsAccountLocalIdFromUid(uid, (err, accountID) => { - console.log('getOsAccountLocalIdFromUid err: ' + JSON.stringify(err)); - console.log('getOsAccountLocalIdFromUid: ' + accountID); - }); + try { + accountManager.queryOsAccountLocalIdFromUid(uid, (err, localId) => { + if (err) { + console.log("queryOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err)); + } + console.log("queryOsAccountLocalIdFromUid successfully, localId: " + localId); + }); + } catch (err) { + console.log("queryOsAccountLocalIdFromUid exception: " + JSON.stringify(err)); + } ``` -### getOsAccountLocalIdFromUid +### queryOsAccountLocalIdFromUid9+ -getOsAccountLocalIdFromUid(uid: number): Promise<number> +queryOsAccountLocalIdFromUid(uid: number): Promise<number> Obtains the OS account ID based on the process UID. This API uses a promise to return the result. @@ -767,27 +1099,38 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | +| Type | Description | +| --------------------- | --------------------------------------- | | Promise<number> | Promise used to return the OS account ID obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid uid. | + **Example**: Obtain the ID of the OS account whose process UID is **12345678**. ```js let accountManager = account_osAccount.getAccountManager(); let uid = 12345678; - accountManager.getOsAccountLocalIdFromUid(uid).then((accountID) => { - console.log('getOsAccountLocalIdFromUid: ' + accountID); - }).catch((err) => { - console.log('getOsAccountLocalIdFromUid err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryOsAccountLocalIdFromUid(uid).then((localId) => { + console.log("queryOsAccountLocalIdFromUid successfully, localId: " + localId); + }).catch((err) => { + console.log("queryOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log('queryOsAccountLocalIdFromUid exception: ' + JSON.stringify(err)); + } ``` -### getOsAccountLocalIdFromDomain8+ +### queryOsAccountLocalIdFromDomain9+ -getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void +queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void -Obtains the OS account ID based on domain account information. This API uses an asynchronous callback to return the result. +Obtains the OS account ID based on the domain account information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -795,27 +1138,41 @@ Obtains the OS account ID based on domain account information. This API uses an **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | -------------------------------------------- | -| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | -| callback | AsyncCallback<number> | Yes | Callback used to return the ID of the OS account associated with the domain account.| +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------------- | ---- | -------------------------------------------------------------------------- | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the ID of the OS account associated with the domain account. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid domainInfo. | **Example** ```js let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountLocalIdFromDomain(domainInfo, (err, accountID) => { - console.log('getOsAccountLocalIdFromDomain: ' + JSON.stringify(err)); - console.log('getOsAccountLocalIdFromDomain: ' + accountID); - }); + try { + accountManager.queryOsAccountLocalIdFromDomain(domainInfo, (err, localId) => { + if (err) { + console.log("queryOsAccountLocalIdFromDomain failed, error: " + JSON.stringify(err)); + } else { + console.log("queryOsAccountLocalIdFromDomain successfully, localId: " + localId); + } + }); + } catch (err) { + console.log('queryOsAccountLocalIdFromDomain exception: ' + JSON.stringify(err)); + } ``` -### getOsAccountLocalIdFromDomain8+ +### queryOsAccountLocalIdFromDomain9+ -getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> +queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> -Obtains the OS account ID based on domain account information. This API uses a promise to return the result. +Obtains the OS account ID based on the domain account information. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -829,20 +1186,31 @@ Obtains the OS account ID based on domain account information. This API uses a p **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | +| Type | Description | +| :-------------------- | :------------------------------------- | | Promise<number> | Promise used to return the ID of the OS account associated with the domain account.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid domainInfo. | + **Example** ```js let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; - accountManager.getOsAccountLocalIdFromDomain(domainInfo).then((accountID) => { - console.log('getOsAccountLocalIdFromDomain: ' + accountID); - }).catch((err) => { - console.log('getOsAccountLocalIdFromDomain err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryOsAccountLocalIdFromDomain(domainInfo).then((localId) => { + console.log("queryOsAccountLocalIdFromDomain successfully, localId: " + localId); + }).catch((err) => { + console.log("queryOsAccountLocalIdFromDomain failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("queryOsAccountLocalIdFromDomain exception: " + JSON.stringify(err)); + } ``` ### queryMaxOsAccountNumber @@ -851,24 +1219,37 @@ queryMaxOsAccountNumber(callback: AsyncCallback<number>): void Obtains the maximum number of OS accounts that can be created. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------------ | -| callback | AsyncCallback<number> | Yes | Callback used to return the maximum number of OS accounts that can be created.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the maximum number of OS accounts that can be created. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryMaxOsAccountNumber((err, maxCnt)=>{ - console.log('queryMaxOsAccountNumber err:' + JSON.stringify(err)); - console.log('queryMaxOsAccountNumber maxCnt:' + maxCnt); - }); + try { + accountManager.queryMaxOsAccountNumber((err, maxCnt) => { + if (err) { + console.log('queryMaxOsAccountNumber failed, error:' + JSON.stringify(err)); + } else { + console.log('queryMaxOsAccountNumber successfully, maxCnt:' + maxCnt); + } + }); + } catch (err) { + console.log('queryMaxOsAccountNumber exception:' + JSON.stringify(err)); + } ``` ### queryMaxOsAccountNumber @@ -877,30 +1258,40 @@ queryMaxOsAccountNumber(): Promise<number> Obtains the maximum number of OS accounts that can be created. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | +| Type | Description | +| --------------------- | ------------------------------------------- | | Promise<number> | Promise used to return the maximum number of OS accounts that can be created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | + **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryMaxOsAccountNumber().then((maxCnt) => { - console.log('queryMaxOsAccountNumber, maxCnt: ' + maxCnt); - }).catch((err) => { - console.log('queryMaxOsAccountNumber err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryMaxOsAccountNumber().then((maxCnt) => { + console.log('queryMaxOsAccountNumber successfully, maxCnt: ' + maxCnt); + }).catch((err) => { + console.log('queryMaxOsAccountNumber failed, error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('queryMaxOsAccountNumber exception:' + JSON.stringify(err)); + } ``` -### getOsAccountAllConstraints +### getOsAccountConstraints9+ -getOsAccountAllConstraints(localId: number, callback: AsyncCallback<Array<string>>): void +getOsAccountConstraints(localId: number, callback: AsyncCallback<Array<string>>): void Obtains all constraints enabled for an OS account. This API uses an asynchronous callback to return the result. @@ -910,25 +1301,40 @@ Obtains all constraints enabled for an OS account. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | -| localId | number | Yes | ID of the target OS account. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return all [constraints](#constraints) obtained.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | -------------------------------------------------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is all [constraints](#constraints) obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Obtain all constraints of OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.getOsAccountAllConstraints(localId, (err, constraints)=>{ - console.log('getOsAccountAllConstraints err:' + JSON.stringify(err)); - console.log('getOsAccountAllConstraints:' + JSON.stringify(constraints)); - }); + try { + accountManager.getOsAccountConstraints(localId, (err, constraints) => { + if (err) { + console.log("getOsAccountConstraints failed, err: " + JSON.stringify(err)); + } else { + console.log("getOsAccountConstraints successfully, constraints: " + JSON.stringify(constraints)); + } + }); + } catch (err) { + console.log('getOsAccountConstraints exception:' + JSON.stringify(err)); + } ``` -### getOsAccountAllConstraints +### getOsAccountConstraints9+ -getOsAccountAllConstraints(localId: number): Promise<Array<string>> +getOsAccountConstraints(localId: number): Promise<Array<string>> Obtains all constraints enabled for an OS account. This API uses a promise to return the result. @@ -944,20 +1350,32 @@ Obtains all constraints enabled for an OS account. This API uses a promise to re **Return value** -| Type | Description | -| :--------------------------------- | :----------------------------------------------------------- | -| Promise<Array<string>> | Promise used to return the [constraints](#constraints) obtained.| +| Type | Description | +| ---------------------------------- | ---------------------------------------------------------- | +| Promise<Array<string>> | Promise used to return all the [constraints](#constraints) enabled for the OS account.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Obtain all constraints of OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.getOsAccountAllConstraints(localId).then((constraints) => { - console.log('getOsAccountAllConstraints, constraints: ' + constraints); - }).catch((err) => { - console.log('getOsAccountAllConstraints err: ' + JSON.stringify(err)); - }); + try { + accountManager.getOsAccountConstraints(localId).then((constraints) => { + console.log('getOsAccountConstraints, constraints: ' + constraints); + }).catch((err) => { + console.log('getOsAccountConstraints err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('getOsAccountConstraints exception:' + JSON.stringify(e)); + } ``` ### queryAllCreatedOsAccounts @@ -966,7 +1384,7 @@ queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>& Obtains information about all the OS accounts created. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -976,16 +1394,26 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | -| callback | AsyncCallback<Array<[OsAccountInfo](#osaccountinfo)>> | Yes | Callback used to return information about OS accounts created.| +| callback | AsyncCallback<Array<[OsAccountInfo](#osaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of all created OS accounts. Otherwise, **data** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryAllCreatedOsAccounts((err, accountArr)=>{ - console.log('queryAllCreatedOsAccounts err:' + JSON.stringify(err)); - console.log('queryAllCreatedOsAccounts accountArr:' + JSON.stringify(accountArr)); - }); + try { + accountManager.queryAllCreatedOsAccounts((err, accountArr)=>{ + console.log('queryAllCreatedOsAccounts err:' + JSON.stringify(err)); + console.log('queryAllCreatedOsAccounts accountArr:' + JSON.stringify(accountArr)); + }); + } catch (e) { + console.log('queryAllCreatedOsAccounts exception:' + JSON.stringify(e)); + } ``` ### queryAllCreatedOsAccounts @@ -994,7 +1422,7 @@ queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> Obtains information about all the OS accounts created. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -1002,24 +1430,34 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| :---------------------------------------------------------- | :----------------------------------------------------------- | -| Promise<Array<[OsAccountInfo](#osaccountinfo)>> | Promise used to return information about OS accounts created.| +| Type | Description | +| ----------------------------------------------------------- | --------------------------------------------- | +| Promise<Array<[OsAccountInfo](#osaccountinfo)>> | Promise used to return the information about all the OS accounts created.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryAllCreatedOsAccounts().then((accountArr) => { - console.log('queryAllCreatedOsAccounts, accountArr: ' + JSON.stringify(accountArr)); - }).catch((err) => { - console.log('queryAllCreatedOsAccounts err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryAllCreatedOsAccounts().then((accountArr) => { + console.log('queryAllCreatedOsAccounts, accountArr: ' + JSON.stringify(accountArr)); + }).catch((err) => { + console.log('queryAllCreatedOsAccounts err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('queryAllCreatedOsAccounts exception:' + JSON.stringify(e)); + } ``` -### queryActivatedOsAccountIds8+ +### getActivatedOsAccountIds9+ -queryActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void +getActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void Obtains information about all activated OS accounts. This API uses an asynchronous callback to return the result. @@ -1029,24 +1467,34 @@ Obtains information about all activated OS accounts. This API uses an asynchrono | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | ------------------------------------------------------ | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return information about activated OS accounts.| +| callback | AsyncCallback<Array<number>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of activated OS accounts. Otherwise, **data** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryActivatedOsAccountIds((err, idArray)=>{ - console.log('queryActivatedOsAccountIds err:' + JSON.stringify(err)); - console.log('queryActivatedOsAccountIds idArray length:' + idArray.length); - for(let i=0;i{ + console.log('getActivatedOsAccountIds err:' + JSON.stringify(err)); + console.log('getActivatedOsAccountIds idArray length:' + idArray.length); + for(let i=0;i8+
+### getActivatedOsAccountIds9+ -queryActivatedOsAccountIds(): Promise<Array<number>> +getActivatedOsAccountIds(): Promise<Array<number>> Obtains information about all activated OS accounts. This API uses a promise to return the result. @@ -1054,19 +1502,29 @@ Obtains information about all activated OS accounts. This API uses a promise to **Return value** -| Type | Description | -| :--------------------------------- | :----------------------------------------------------------- | -| Promise<Array<number>> | Promise used to return information about activated OS accounts.| +| Type | Description | +| :--------------------------------- | :------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the information about all activated OS accounts.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryActivatedOsAccountIds().then((idArray) => { - console.log('queryActivatedOsAccountIds, idArray: ' + idArray); - }).catch((err) => { - console.log('queryActivatedOsAccountIds err: ' + JSON.stringify(err)); - }); + try { + accountManager.getActivatedOsAccountIds().then((idArray) => { + console.log('getActivatedOsAccountIds, idArray: ' + idArray); + }).catch((err) => { + console.log('getActivatedOsAccountIds err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('getActivatedOsAccountIds exception:' + JSON.stringify(e)); + } ``` ### createOsAccount @@ -1075,7 +1533,7 @@ createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback& Creates an OS account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1083,20 +1541,34 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| :-------- | ---------------------------------------------------- | ---- | ------------------------------------------ | -| localName | string | Yes | Name of the OS account to create. | -| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | -| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| +| Name | Type | Mandatory| Description | +| :-------- | ---------------------------------------------------- | ---- | --------------------------------------------------------------------------- | +| localName | string | Yes | Name of the OS account to create. | +| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | +| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the created OS account. Otherwise, **err** is an error object.| + +**Error codes** + +| ID | Error Message | +| -------- | ------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localName or type. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.createOsAccount('testName', account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ - console.log('createOsAccount err:' + JSON.stringify(err)); - console.log('createOsAccount osAccountInfo:' + JSON.stringify(osAccountInfo)); - }); + try { + accountManager.createOsAccount('testName', account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + console.log('createOsAccount err:' + JSON.stringify(err)); + console.log('createOsAccount osAccountInfo:' + JSON.stringify(osAccountInfo)); + }); + } catch (e) { + console.log('createOsAccount exception:' + JSON.stringify(e)); + } ``` ### createOsAccount @@ -1105,7 +1577,7 @@ createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInf Creates an OS account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1120,19 +1592,33 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| :--------------------------------------------- | :----------------------------------------------------------- | -| Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account created.| +| Type | Description | +| ---------------------------------------------- | ------------------------------------- | +| Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the information about the created OS account.| + +**Error codes** + +| ID | Error Message | +| -------- | ------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localName or type. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.createOsAccount('testAccountName', account_osAccount.OsAccountType.NORMAL).then((accountInfo) => { - console.log('createOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); - }).catch((err) => { - console.log('createOsAccount err: ' + JSON.stringify(err)); - }); + try { + accountManager.createOsAccount('testAccountName', account_osAccount.OsAccountType.NORMAL).then((accountInfo) => { + console.log('createOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log('createOsAccount err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('createOsAccount exception:' + JSON.stringify(e)); + } ``` ### createOsAccountForDomain8+ @@ -1141,7 +1627,7 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, cal Creates an OS account and associates it with the specified domain account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1149,21 +1635,35 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| :--------- | ---------------------------------------------------- | ---- | ------------------------------------------ | -| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | -| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | -| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------------------------------------------------- | +| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | +| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the created OS account. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or domainInfo. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; - accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo, (err, osAccountInfo)=>{ - console.log('createOsAccountForDomain err:' + JSON.stringify(err)); - console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo)); - }); + try { + accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo, (err, osAccountInfo)=>{ + console.log('createOsAccountForDomain err:' + JSON.stringify(err)); + console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo)); + }); + } catch (e) { + console.log('createOsAccountForDomain exception:' + JSON.stringify(e)); + } ``` ### createOsAccountForDomain8+ @@ -1172,7 +1672,7 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Pr Creates an OS account and associates it with the specified domain account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1180,32 +1680,46 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ---------------------- | -| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | -------------------- | +| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | **Return value** -| Type | Description | -| :--------------------------------------------- | :----------------------------------------------------------- | +| Type | Description | +| ---------------------------------------------- | -------------------------------------- | | Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or domainInfo. | +| 12300005 | Multi-user not supported. | +| 12300006 | Unsupported account type. | +| 12300007 | The number of account reaches the upper limit. | + **Example** ```js let accountManager = account_osAccount.getAccountManager(); let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; - accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo).then((accountInfo) => { - console.log('createOsAccountForDomain, account info: ' + JSON.stringify(accountInfo)); - }).catch((err) => { - console.log('createOsAccountForDomain err: ' + JSON.stringify(err)); - }); + try { + accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo).then((accountInfo) => { + console.log('createOsAccountForDomain, account info: ' + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log('createOsAccountForDomain err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('createOsAccountForDomain exception:' + JSON.stringify(e)); + } ``` -### queryCurrentOsAccount +### getCurrentOsAccount9+ -queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void +getCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void Obtains information about the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. @@ -1217,21 +1731,31 @@ Obtains information about the OS account to which the current process belongs. T | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | -| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return information about the OS account obtained.| +| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account information obtained. Otherwise, **data** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryCurrentOsAccount((err, curAccountInfo)=>{ - console.log('queryCurrentOsAccount err:' + JSON.stringify(err)); - console.log('queryCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); - }); + try { + accountManager.getCurrentOsAccount((err, curAccountInfo)=>{ + console.log('getCurrentOsAccount err:' + JSON.stringify(err)); + console.log('getCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); + }); + } catch (e) { + console.log('getCurrentOsAccount exception:' + JSON.stringify(e)); + } ``` -### queryCurrentOsAccount +### getCurrentOsAccount9+ -queryCurrentOsAccount(): Promise<OsAccountInfo> +getCurrentOsAccount(): Promise<OsAccountInfo> Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result. @@ -1241,28 +1765,38 @@ Obtains information about the OS account to which the current process belongs. T **Return value** -| Type | Description | -| :--------------------------------------------- | :----------------------------------------------------------- | -| Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return information about the OS account obtained.| +| Type | Description | +| ---------------------------------------------- | ----------------------------------------- | +| Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account information obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryCurrentOsAccount().then((accountInfo) => { - console.log('queryCurrentOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); - }).catch((err) => { - console.log('queryCurrentOsAccount err: ' + JSON.stringify(err)); - }); + try { + accountManager.getCurrentOsAccount().then((accountInfo) => { + console.log('getCurrentOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log('getCurrentOsAccount err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('getCurrentOsAccount exception:' + JSON.stringify(e)); + } ``` ### queryOsAccountById queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo>): void -Obtains information about an OS account. This API uses an asynchronous callback to return the result. +Obtains information about the OS account of the given ID. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION @@ -1270,29 +1804,41 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------- | ---- | ---------------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account information obtained.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------------------ | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account information obtained. Otherwise, **data** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Query information about OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.queryOsAccountById(localId, (err, accountInfo)=>{ - console.log('queryOsAccountById err:' + JSON.stringify(err)); - console.log('queryOsAccountById accountInfo:' + JSON.stringify(accountInfo)); - }); + try { + accountManager.queryOsAccountById(localId, (err, accountInfo)=>{ + console.log('queryOsAccountById err:' + JSON.stringify(err)); + console.log('queryOsAccountById accountInfo:' + JSON.stringify(accountInfo)); + }); + } catch (e) { + console.log('queryOsAccountById exception:' + JSON.stringify(e)); + } ``` ### queryOsAccountById queryOsAccountById(localId: number): Promise<OsAccountInfo> -Obtains information about an OS account. This API uses a promise to return the result. +Obtains information about the OS account of the given ID. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION @@ -1306,27 +1852,39 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| :--------------------------------------------- | :----------------------------------------------------------- | +| Type | Description | +| ---------------------------------------------- | ------------------------------------ | | Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account information obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | + **Example**: Query information about OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.queryOsAccountById(localId).then((accountInfo) => { - console.log('queryOsAccountById, accountInfo: ' + JSON.stringify(accountInfo)); - }).catch((err) => { - console.log('queryOsAccountById err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryOsAccountById(localId).then((accountInfo) => { + console.log('queryOsAccountById, accountInfo: ' + JSON.stringify(accountInfo)); + }).catch((err) => { + console.log('queryOsAccountById err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('queryOsAccountById exception:' + JSON.stringify(e)); + } ``` -### getOsAccountTypeFromProcess +### getOsAccountType9+ -getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void +getOsAccountType(callback: AsyncCallback<OsAccountType>): void -Obtains the type of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. +Obtains the type of the account to which the current process belongs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1334,21 +1892,31 @@ Obtains the type of the OS account to which the current process belongs. This AP | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------------- | ---- | ---------------------------------------------------- | -| callback | AsyncCallback<[OsAccountType](#osaccounttype)> | Yes | Callback used to return the OS account type.| +| callback | AsyncCallback<[OsAccountType](#osaccounttype)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account type obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountTypeFromProcess((err, accountType) => { - console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); - console.log('getOsAccountTypeFromProcess accountType: ' + accountType); - }); + try { + accountManager.getOsAccountType((err, accountType) => { + console.log('getOsAccountType err: ' + JSON.stringify(err)); + console.log('getOsAccountType accountType: ' + accountType); + }); + } catch (e) { + console.log('getOsAccountType exception: ' + JSON.stringify(e)); + } ``` -### getOsAccountTypeFromProcess +### getOsAccountType9+ -getOsAccountTypeFromProcess(): Promise<OsAccountType> +getOsAccountType(): Promise<OsAccountType> Obtains the type of the OS account to which the current process belongs. This API uses a promise to return the result. @@ -1356,24 +1924,34 @@ Obtains the type of the OS account to which the current process belongs. This AP **Return value** -| Type | Description | -| :--------------------------------------------- | :----------------------------------------------------------- | -| Promise<[OsAccountType](#osaccounttype)> | Promise used to return the OS account type.| +| Type | Description | +| ---------------------------------------------- | ----------------------------------------------- | +| Promise<[OsAccountType](#osaccounttype)> | Promise used to return the OS account type obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getOsAccountTypeFromProcess().then((accountType) => { - console.log('getOsAccountTypeFromProcess, accountType: ' + accountType); - }).catch((err) => { - console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); - }); + try { + accountManager.getOsAccountType().then((accountType) => { + console.log('getOsAccountType, accountType: ' + accountType); + }).catch((err) => { + console.log('getOsAccountType err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('getOsAccountType exception: ' + JSON.stringify(e)); + } ``` -### getDistributedVirtualDeviceId +### queryDistributedVirtualDeviceId9+ -getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void +queryDistributedVirtualDeviceId(callback: AsyncCallback<string>): void Obtains the ID of this distributed virtual device. This API uses an asynchronous callback to return the result. @@ -1383,23 +1961,33 @@ Obtains the ID of this distributed virtual device. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback<string> | Yes | Callback used to return the device ID obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------------------------- | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the distributed virtual device ID obtained. Otherwise, **data** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getDistributedVirtualDeviceId((err, virtualID) => { - console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); - console.log('getDistributedVirtualDeviceId virtualID: ' + virtualID); - }); + try { + accountManager.queryDistributedVirtualDeviceId((err, virtualID) => { + console.log('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); + console.log('queryDistributedVirtualDeviceId virtualID: ' + virtualID); + }); + } catch (e) { + console.log('queryDistributedVirtualDeviceId exception: ' + JSON.stringify(e)); + } ``` -### getDistributedVirtualDeviceId +### queryDistributedVirtualDeviceId9+ -getDistributedVirtualDeviceId(): Promise<string> +queryDistributedVirtualDeviceId(): Promise<string> Obtains the ID of this distributed virtual device. This API uses a promise to return the result. @@ -1409,19 +1997,29 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<string> | Promise used to return the device ID obtained.| +| Type | Description | +| --------------------- | --------------------------------- | +| Promise<string> | Promise used to return the distributed virtual device ID obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | **Example** ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.getDistributedVirtualDeviceId().then((virtualID) => { - console.log('getDistributedVirtualDeviceId, virtualID: ' + virtualID); - }).catch((err) => { - console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryDistributedVirtualDeviceId().then((virtualID) => { + console.log('queryDistributedVirtualDeviceId, virtualID: ' + virtualID); + }).catch((err) => { + console.log('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('queryDistributedVirtualDeviceId exception: ' + JSON.stringify(e)); + } ``` ### getOsAccountProfilePhoto @@ -1430,7 +2028,7 @@ getOsAccountProfilePhoto(localId: number, callback: AsyncCallback<string>) Obtains the profile photo of an OS account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1438,20 +2036,32 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| callback | AsyncCallback<string> | Yes | Callback used to return the profile photo obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the profile photo information obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Obtain the profile photo of OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.getOsAccountProfilePhoto(localId, (err, photo)=>{ - console.log('getOsAccountProfilePhoto err:' + JSON.stringify(err)); - console.log('get photo:' + photo + ' by localId: ' + localId); - }); + try { + accountManager.getOsAccountProfilePhoto(localId, (err, photo)=>{ + console.log('getOsAccountProfilePhoto err:' + JSON.stringify(err)); + console.log('get photo:' + photo + ' by localId: ' + localId); + }); + } catch (e) { + console.log('getOsAccountProfilePhoto exception:' + JSON.stringify(e)); + } ``` ### getOsAccountProfilePhoto @@ -1460,7 +2070,7 @@ getOsAccountProfilePhoto(localId: number): Promise<string> Obtains the profile photo of an OS account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1474,20 +2084,32 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<string> | Promise used to return the profile photo obtained.| +| Type | Description | +| --------------------- | -------------------------------------- | +| Promise<string> | Promise used to return the profile photo information obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Obtain the profile photo of OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.getOsAccountProfilePhoto(localId).then((photo) => { - console.log('getOsAccountProfilePhoto: ' + photo); - }).catch((err) => { - console.log('getOsAccountProfilePhoto err: ' + JSON.stringify(err)); - }); + try { + accountManager.getOsAccountProfilePhoto(localId).then((photo) => { + console.log('getOsAccountProfilePhoto: ' + photo); + }).catch((err) => { + console.log('getOsAccountProfilePhoto err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('getOsAccountProfilePhoto exception:' + JSON.stringify(e)); + } ``` ### setOsAccountProfilePhoto @@ -1496,7 +2118,7 @@ setOsAccountProfilePhoto(localId: number, photo: string, callback: AsyncCallback Sets a profile photo for an OS account. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1508,7 +2130,16 @@ This is a system API and cannot be called by third-party applications. | -------- | ------------------------- | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| | photo | string | Yes | Profile photo information. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or photo. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example**: Set a profile photo for OS account 100. @@ -1519,9 +2150,13 @@ This is a system API and cannot be called by third-party applications. 'Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y'+ 'q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo'+ '+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==' - accountManager.setOsAccountProfilePhoto(localId, photo, (err)=>{ - console.log('setOsAccountProfilePhoto err:' + JSON.stringify(err)); - }); + try { + accountManager.setOsAccountProfilePhoto(localId, photo, (err)=>{ + console.log('setOsAccountProfilePhoto err:' + JSON.stringify(err)); + }); + } catch (e) { + console.log('setOsAccountProfilePhoto exception:' + JSON.stringify(e)); + } ``` ### setOsAccountProfilePhoto @@ -1530,7 +2165,7 @@ setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> Sets a profile photo for an OS account. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1545,9 +2180,18 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| :------------------ | :---------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or photo. | +| 12300003 | Account not found. | +| 12300008 | Restricted Account. | **Example**: Set a profile photo for OS account 100. @@ -1558,42 +2202,58 @@ This is a system API and cannot be called by third-party applications. 'Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y'+ 'q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo'+ '+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==' - accountManager.setOsAccountProfilePhoto(localId, photo).then(() => { - console.log('setOsAccountProfilePhoto success'); - }).catch((err) => { - console.log('setOsAccountProfilePhoto err: ' + JSON.stringify(err)); - }); + try { + accountManager.setOsAccountProfilePhoto(localId, photo).then(() => { + console.log('setOsAccountProfilePhoto success'); + }).catch((err) => { + console.log('setOsAccountProfilePhoto err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('setOsAccountProfilePhoto exception:' + JSON.stringify(e)); + } ``` -### getOsAccountLocalIdBySerialNumber8+ +### queryOsAccountLocalIdBySerialNumber9+ -getOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void +queryOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void -Obtains the OS account ID based on the SN. This API uses an asynchronous callback to return the result. +Obtains the OS account ID based on the serial number (SN). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | --------------------------- | ---- | ------------------------------------------------ | -| serialNumber | number | Yes | Account SN. | -| callback | AsyncCallback<number> | Yes | Callback used to return the OS account ID obtained.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------- | ---- | ---------------------------------------------------------------------------- | +| serialNumber | number | Yes | Account SN. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account ID obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid serialNumber. | +| 12300003 | Account not found. | **Example**: Obtain the ID of the OS account whose SN is 12345. ```js let accountManager = account_osAccount.getAccountManager(); let serialNumber = 12345; - accountManager.getOsAccountLocalIdBySerialNumber(serialNumber, (err, localId)=>{ - console.log('ger localId err:' + JSON.stringify(err)); - console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); - }); + try { + accountManager.queryOsAccountLocalIdBySerialNumber(serialNumber, (err, localId)=>{ + console.log('ger localId err:' + JSON.stringify(err)); + console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); + }); + } catch (e) { + console.log('ger localId exception:' + JSON.stringify(e)); + } ``` -### getOsAccountLocalIdBySerialNumber8+ +### queryOsAccountLocalIdBySerialNumber9+ -getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> +queryOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> Obtains the OS account ID based on the SN. This API uses a promise to return the result. @@ -1607,25 +2267,37 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | +| Type | Description | +| --------------------- | -------------------------------------------- | | Promise<number> | Promise used to return the OS account ID obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid serialNumber. | +| 12300003 | Account not found. | + **Example**: Obtain the ID of the OS account whose SN is 12345. ```js let accountManager = account_osAccount.getAccountManager(); let serialNumber = 12345; - accountManager.getOsAccountLocalIdBySerialNumber(serialNumber).then((localId) => { - console.log('getOsAccountLocalIdBySerialNumber localId: ' + localId); - }).catch((err) => { - console.log('getOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err)); - }); + try { + accountManager.queryOsAccountLocalIdBySerialNumber(serialNumber).then((localId) => { + console.log('queryOsAccountLocalIdBySerialNumber localId: ' + localId); + }).catch((err) => { + console.log('queryOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('queryOsAccountLocalIdBySerialNumber exception: ' + JSON.stringify(e)); + } ``` -### getSerialNumberByOsAccountLocalId8+ +### querySerialNumberByOsAccountLocalId9+ -getSerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void +querySerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void Obtains the SN of an OS account based on the account ID. This API uses an asynchronous callback to return the result. @@ -1633,25 +2305,37 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------ | -| localId | number | Yes | ID of the target OS account. | -| callback | AsyncCallback<number> | Yes | Callback used to return the account SN obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the SN obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Obtain the SN of the OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.getSerialNumberByOsAccountLocalId(localId, (err, serialNumber)=>{ - console.log('ger serialNumber err:' + JSON.stringify(err)); - console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); - }); + try { + accountManager.querySerialNumberByOsAccountLocalId(localId, (err, serialNumber)=>{ + console.log('ger serialNumber err:' + JSON.stringify(err)); + console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); + }); + } catch (e) { + console.log('ger serialNumber exception:' + JSON.stringify(e)); + } ``` -### getSerialNumberByOsAccountLocalId8+ +### querySerialNumberByOsAccountLocalId9+ -getSerialNumberByOsAccountLocalId(localId: number): Promise<number> +querySerialNumberByOsAccountLocalId(localId: number): Promise<number> Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result. @@ -1659,267 +2343,1452 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------ | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------- | | localId | number | Yes | ID of the target OS account.| **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<number> | Promise used to return the account SN obtained.| +| Type | Description | +| :-------------------- | :------------------------------------- | +| Promise<number> | Promise used to return the SN obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId. | +| 12300003 | Account not found. | **Example**: Obtain the SN of the OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); let localId = 100; - accountManager.getSerialNumberByOsAccountLocalId(localId).then((serialNumber) => { - console.log('getSerialNumberByOsAccountLocalId serialNumber: ' + serialNumber); + try { + accountManager.querySerialNumberByOsAccountLocalId(localId).then((serialNumber) => { + console.log('querySerialNumberByOsAccountLocalId serialNumber: ' + serialNumber); + }).catch((err) => { + console.log('querySerialNumberByOsAccountLocalId err: ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('querySerialNumberByOsAccountLocalId exception:' + JSON.stringify(e)); + } + ``` + +### on + +on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void + +Subscribes to OS account changes. This API uses a callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| type | 'activate' \| 'activating' | Yes | Type of the event to subscribe to. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| +| name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes. | +| callback | Callback<number> | Yes | Callback invoked to return the OS account ID and status changes. | + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or name. | +| 12300011 | Callback has been registered. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + function onCallback(receiveLocalId){ + console.log('receive localId:' + receiveLocalId); + } + try { + accountManager.on('activating', 'osAccountOnOffNameA', onCallback); + } catch (e) { + console.log('receive localId exception:' + JSON.stringify(e)); + } + ``` + +### off + +off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void + +Unsubscribes from OS account changes. This API uses a callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| type | 'activate' \| 'activating' | Yes | Type of the event to unsubscribe from. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| +| name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes, and must be the same as the value passed by **on()**.| +| callback | Callback<number> | No | Callback for OS account changes. By default, **0** is returned. | + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or name. | +| 12300012 | Callback has not been registered. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + function offCallback(){ + console.log('off enter') + } + try { + accountManager.off('activating', 'osAccountOnOffNameA', offCallback); + } catch (e) { + console.log('off exception:' + JSON.stringify(e)); + } + ``` + +### getBundleIdFromUid9+ + +getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; + +Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------------------ | +| uid | number | Yes | Process UID. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the bundle ID obtained. Otherwise, **data** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid uid. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + let testUid = 1000000; + try { + accountManager.getBundleIdFromUid(testUid, (err, bundleId) => { + console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err)); + console.info('getBundleIdFromUid bundleId:' + JSON.stringify(bundleId)); + }); + } catch (e) { + console.info('getBundleIdFromUid exception:' + JSON.stringify(e)); + } + ``` +### getBundleIdFromUid9+ + +getBundleIdFromUid(uid: number): Promise<number>; + +Obtains the bundle ID based on the UID. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------ | +| uid | number | Yes | Process UID.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------ | +| Promise<number> | Promise used to return the bundle ID obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid uid. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + let testUid = 1000000; + try { + accountManager.getBundleIdFromUid(testUid).then((result) => { + console.info('getBundleIdFromUid bundleId:' + JSON.stringify(result)); + }).catch((err)=>{ + console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err)); + }); + } catch (e) { + console.info('getBundleIdFromUid exception:' + JSON.stringify(e)); + } + ``` + +### isMainOsAccount9+ + +isMainOsAccount(callback: AsyncCallback<boolean>): void; + +Checks whether the current process belongs to the main OS account. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ----------------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the current process belongs to the main OS account. If **false** is returned, the current process does not belong to the main OS account.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + try { + accountManager.isMainOsAccount((err,result)=>{ + console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); + console.info('isMainOsAccount result:' + JSON.stringify(result)); + }); + } catch (e) { + console.info('isMainOsAccount exception:' + JSON.stringify(e)); + } + ``` +### isMainOsAccount9+ + +isMainOsAccount(): Promise<boolean>; + +Checks whether the current process belongs to the main OS account. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the current process belongs to the main OS account. If **false** is returned, the current process does not belong to the main OS account.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + try { + accountManager.isMainOsAccount().then((result) => { + console.info('isMainOsAccount result:' + JSON.stringify(result)); + }).catch((err)=>{ + console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); + }); + } catch (e) { + console.info('isMainOsAccount exception:' + JSON.stringify(e)); + } + ``` +### queryOsAccountConstraintSourceTypes9+ + +queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; + +Obtains the constraint source information of an OS account. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------------------------ | +| localId | number | Yes | ID of the target OS account.| +| constraint | string | Yes | Name of the [constraint](#constraints) to query.| +| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the [constraint](#constraints) source information obtained. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or constraint. | +| 12300003 | Account not found. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + try { + accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi',(err,sourceTypeInfos)=>{ + console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err)); + console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(sourceTypeInfos)); + }); + } catch (e) { + console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); + } + ``` + +### queryOsAccountConstraintSourceTypes9+ + +queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>; + +Obtains the constraint source information of an OS account. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------ | +| localId | number | Yes | ID of the target OS account.| +| constraint | string | Yes | Name of the [constraint](#constraints) to query.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------------------ | +| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the [constraint](#constraints) source information obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid localId or constraint. | +| 12300003 | Account not found. | + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + try { + accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi').then((result) => { + console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(result)); + }).catch((err)=>{ + console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err)); + }); + } catch (e) { + console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); + } + ``` + +### isMultiOsAccountEnable(deprecated) + +isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void + +Checks whether multiple OS accounts are supported. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkMultiOsAccountEnabled](#checkmultiosaccountenabled9). + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.isMultiOsAccountEnable((err, isEnabled) => { + if (err) { + console.log("isMultiOsAccountEnable failed, error: " + JSON.stringify(err)); + } else { + console.log("isMultiOsAccountEnable successfully, isEnabled: " + isEnabled); + } + }); + ``` + +### isMultiOsAccountEnable(deprecated) + +isMultiOsAccountEnable(): Promise<boolean> + +Checks whether multiple OS accounts are supported. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkMultiOsAccountEnabled](#checkmultiosaccountenabled9-1). + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| :--------------------- | :--------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, multiple OS accounts are supported. If **false** is returned, multiple OS accounts are not supported.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.isMultiOsAccountEnable().then((isEnabled) => { + console.log('isMultiOsAccountEnable successfully, isEnabled: ' + isEnabled); + }).catch((err) => { + console.log('isMultiOsAccountEnable failed, error: ' + JSON.stringify(err)); + }); + ``` + + +### isOsAccountActived(deprecated) + +isOsAccountActived(localId: number, callback: AsyncCallback<boolean>): void + +Checks whether an OS account is activated. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountActivated](#checkosaccountactivated9). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------ | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| + +**Example**: Check whether OS account 100 is activated. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let localId = 100; + accountManager.isOsAccountActived(localId, (err, isActived) => { + if (err) { + console.log('isOsAccountActived failed, err:' + JSON.stringify(err)); + } else { + console.log('isOsAccountActived successfully, isActived:' + isActived); + } + }); + ``` + +### isOsAccountActived(deprecated) + +isOsAccountActived(localId: number): Promise<boolean> + +Checks whether an OS account is activated. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountActivated](#checkosaccountactivated9-1). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------- | +| localId | number | Yes | ID of the target OS account.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is activated. If **false** is returned, the account is not activated.| + +**Example**: Check whether OS account 100 is activated. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let localId = 100; + accountManager.isOsAccountActived(localId).then((isActived) => { + console.log('isOsAccountActived successfully, isActived: ' + isActived); + }).catch((err) => { + console.log('isOsAccountActived failed, error: ' + JSON.stringify(err)); + }); + ``` + +### isOsAccountConstraintEnable(deprecated) + +isOsAccountConstraintEnable(localId: number, constraint: string, callback: AsyncCallback<boolean>): void + +Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkConstraintEnabled](#checkconstraintenabled9). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------- | ---- | ----------------------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| constraint | string | Yes | [Constraint](#constraints) to check. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| + +**Example**: Check whether OS account 100 is forbidden to use Wi-Fi. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let localId = 100; + let constraint = "constraint.wifi"; + accountManager.isOsAccountConstraintEnable(localId, constraint, (err, isEnabled) => { + if (err) { + console.log("isOsAccountConstraintEnable failed, error:" + JSON.stringify(err)); + } else { + console.log("isOsAccountConstraintEnable successfully, isEnabled:" + isEnabled); + } + }); + ``` + +### isOsAccountConstraintEnable(deprecated) + +isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boolean> + +Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkConstraintEnabled](#checkconstraintenabled9-1). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ---------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| constraint | string | Yes | [Constraint](#constraints) to check.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the constraint is enabled. If **false** is returned, the constraint is not enabled.| + +**Example**: Check whether OS account 100 is forbidden to use Wi-Fi. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let localId = 100; + let constraint = "constraint.wifi"; + accountManager.isOsAccountConstraintEnable(localId, constraint).then((isEnabled) => { + console.log("isOsAccountConstraintEnable successfully, isEnabled: " + isEnabled); + }).catch((err) => { + console.log("isOsAccountConstraintEnable err: " + JSON.stringify(err)); + }); + ``` + +### isTestOsAccount(deprecated) + +isTestOsAccount(callback: AsyncCallback<boolean>): void + +Checks whether this OS account is a test account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountTestable](#checkosaccounttestable9). + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | --------------------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.isTestOsAccount((err, isTestable) => { + if (err) { + console.log("isTestOsAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("isTestOsAccount successfully, isTestable: " + isTestable); + } + }); + ``` + +### isTestOsAccount(deprecated) + +isTestOsAccount(): Promise<boolean> + +Checks whether this OS account is a test account. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountTestable](#checkosaccounttestable9-1). + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the account is a test account. If **false** is returned, the account is not a test account.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.isTestOsAccount().then((isTestable) => { + console.log("isTestOsAccount successfully, isTestable: " + isTestable); + }).catch((err) => { + console.log("isTestOsAccount failed, error: " + JSON.stringify(err)); + }); + ``` + +### isOsAccountVerified(deprecated) + +isOsAccountVerified(callback: AsyncCallback<boolean>): void + +Checks whether this OS account has been verified. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountVerified](#checkosaccountverified9). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.isOsAccountVerified((err, isVerified) => { + if (err) { + console.log("isOsAccountVerified failed, error: " + JSON.stringify(err)); + } else { + console.log("isOsAccountVerified successfully, isVerified: " + isVerified); + } + }); + ``` + +### isOsAccountVerified(deprecated) + +isOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void + +Checks whether an OS account has been verified. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountVerified](#checkosaccountverified9-1). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------- | +| localId | number | No | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + let localId = 100; + accountManager.isOsAccountVerified(localId, (err, isVerified) => { + if (err) { + console.log("isOsAccountVerified failed, error: " + JSON.stringify(err)); + } else { + console.log("isOsAccountVerified successfully, isVerified: " + isVerified); + } + }); + ``` + +### isOsAccountVerified(deprecated) + +isOsAccountVerified(localId?: number): Promise<boolean> + +Checks whether an OS account has been verified. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountVerified](#checkosaccountverified9-2). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------------------------------------------- | +| localId | number | No | ID of the target OS account. If this parameter is not specified, this API checks whether the current OS account has been verified.| + +**Return value** + +| Type | Description | +| ---------------------- | ----------------------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, the account has been verified. If **false** is returned, the account has not been verified.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.isOsAccountVerified(localId).then((isVerified) => { + console.log("isOsAccountVerified successfully, isVerified: " + isVerified); + }).catch((err) => { + console.log("isOsAccountVerified failed, error: " + JSON.stringify(err)); + }); + ``` + +### getCreatedOsAccountsCount(deprecated) + +getCreatedOsAccountsCount(callback: AsyncCallback<number>): void + +Obtains the number of OS accounts created. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountCount](#getosaccountcount9). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the number of created OS accounts. If the operation fails, **err** is an error object.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.getCreatedOsAccountsCount((err, count)=>{ + if (err) { + console.log("getCreatedOsAccountsCount failed, error: " + JSON.stringify(err)); + } else { + console.log("getCreatedOsAccountsCount successfully, count: " + count); + } + }); + ``` + +### getCreatedOsAccountsCount(deprecated) + +getCreatedOsAccountsCount(): Promise<number> + +Obtains the number of OS accounts created. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountCount](#getosaccountcount9-1). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| --------------------- | -------------------------------------- | +| Promise<number> | Promise used to return the number of created OS accounts.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.getCreatedOsAccountsCount().then((count) => { + console.log("getCreatedOsAccountsCount successfully, count: " + count); + }).catch((err) => { + console.log("getCreatedOsAccountsCount failed, error: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountLocalIdFromProcess(deprecated) + +getOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void + +Obtains the ID of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromProcess](#queryosaccountlocalidfromprocess9). + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------------------------------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account ID obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountLocalIdFromProcess((err, localId) => { + if (err) { + console.log("getOsAccountLocalIdFromProcess failed, error: " + JSON.stringify(err)); + } else { + console.log("getOsAccountLocalIdFromProcess successfully, localId: " + localId); + } + }); + ``` + +### getOsAccountLocalIdFromProcess(deprecated) + +getOsAccountLocalIdFromProcess(): Promise<number> + +Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromProcess](#queryosaccountlocalidfromprocess9-1). + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| :-------------------- | :--------------------------------------- | +| Promise<number> | Promise used to return the OS account ID obtained.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountLocalIdFromProcess().then((localId) => { + console.log('getOsAccountLocalIdFromProcess successfully, localId: ' + localId); + }).catch((err) => { + console.log('getOsAccountLocalIdFromProcess failed, error: ' + JSON.stringify(err)); + }); + ``` + +### getOsAccountLocalIdFromUid(deprecated) + +getOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void + +Obtains the OS account ID based on the process UID. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromUid](#queryosaccountlocalidfromuid9). + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------------------------- | +| uid | number | Yes | Process UID. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account ID obtained. Otherwise, **data** is an error object.| + +**Example**: Obtain the ID of the OS account whose process UID is **12345678**. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let uid = 12345678; + accountManager.getOsAccountLocalIdFromUid(uid, (err, localId) => { + if (err) { + console.log("getOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err)); + } else { + console.log("getOsAccountLocalIdFromUid successfully, localId: " + localId); + } + }); + ``` + +### getOsAccountLocalIdFromUid(deprecated) + +getOsAccountLocalIdFromUid(uid: number): Promise<number> + +Obtains the OS account ID based on the process UID. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromUid](#queryosaccountlocalidfromuid9-1). + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------- | +| uid | number | Yes | Process UID.| + +**Return value** + +| Type | Description | +| :-------------------- | :----------------------------------- | +| Promise<number> | Promise used to return the OS account ID obtained.| + +**Example**: Obtain the ID of the OS account whose process UID is **12345678**. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let uid = 12345678; + accountManager.getOsAccountLocalIdFromUid(uid).then((localId) => { + console.log("getOsAccountLocalIdFromUid successfully, localId: " + localId); + }).catch((err) => { + console.log("getOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err)); + }); + ``` + +### getOsAccountLocalIdFromDomain(deprecated) + +getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void + +Obtains the OS account ID based on the domain account information. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromDomain](#queryosaccountlocalidfromdomain9). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------------- | ---- | --------------------------------------------------------------------------- | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account ID obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + let accountManager = account_osAccount.getAccountManager(); + accountManager.getOsAccountLocalIdFromDomain(domainInfo, (err, localId) => { + if (err) { + console.log("getOsAccountLocalIdFromDomain failed, error: " + JSON.stringify(err)); + } else { + console.log("getOsAccountLocalIdFromDomain successfully, localId: " + localId); + } + }); + ``` + +### getOsAccountLocalIdFromDomain(deprecated) + +getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> + +Obtains the OS account ID based on the domain account information. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromDomain](#queryosaccountlocalidfromdomain9-1). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------------- | ---- | ------------ | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| + +**Return value** + +| Type | Description | +| :-------------------- | :------------------------------------- | +| Promise<number> | Promise used to return the OS account ID obtained.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + accountManager.getOsAccountLocalIdFromDomain(domainInfo).then((localId) => { + console.log('getOsAccountLocalIdFromDomain successfully, localId: ' + localId); + }).catch((err) => { + console.log('getOsAccountLocalIdFromDomain failed, error: ' + JSON.stringify(err)); + }); + ``` + +### getOsAccountAllConstraints(deprecated) + +getOsAccountAllConstraints(localId: number, callback: AsyncCallback<Array<string>>): void + +Obtains all constraints enabled for an OS account. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountConstraints](#getosaccountconstraints9). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------------------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of all [constraints](#constraints) enabled for the OS account. Otherwise, **err** is an error object.| + +**Example**: Obtain all constraints of OS account 100. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let localId = 100; + accountManager.getOsAccountAllConstraints(localId, (err, constraints)=>{ + console.log('getOsAccountAllConstraints err:' + JSON.stringify(err)); + console.log('getOsAccountAllConstraints:' + JSON.stringify(constraints)); + }); + ``` + +### getOsAccountAllConstraints(deprecated) + +getOsAccountAllConstraints(localId: number): Promise<Array<string>> + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountConstraints](#getosaccountconstraints9-1). + +Obtains all constraints enabled for an OS account. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------ | +| localId | number | Yes | ID of the target OS account.| + +**Return value** + +| Type | Description | +| :--------------------------------- | :----------------------------------------------------------- | +| Promise<Array<string>> | Promise used to return all the [constraints](#constraints) enabled for the OS account.| + +**Example**: Obtain all constraints of OS account 100. + + ```js + let accountManager = account_osAccount.getAccountManager(); + let localId = 100; + accountManager.getOsAccountAllConstraints(localId).then((constraints) => { + console.log('getOsAccountAllConstraints, constraints: ' + constraints); + }).catch((err) => { + console.log('getOsAccountAllConstraints err: ' + JSON.stringify(err)); + }); + ``` + +### queryActivatedOsAccountIds(deprecated) + +queryActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void + +Obtains information about all activated OS accounts. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountIds](#getactivatedosaccountids9). + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------------------------ | +| callback | AsyncCallback<Array<number>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of activated OS accounts. Otherwise, **data** is an error object.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.queryActivatedOsAccountIds((err, idArray)=>{ + console.log('queryActivatedOsAccountIds err:' + JSON.stringify(err)); + console.log('queryActivatedOsAccountIds idArray length:' + idArray.length); + for(let i=0;i(deprecated)
+ +queryActivatedOsAccountIds(): Promise<Array<number>> + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountIds](#getactivatedosaccountids9-1). + +Obtains information about all activated OS accounts. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------- | +| Promise<Array<number>> | Promise used to return the information about all activated OS accounts.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.queryActivatedOsAccountIds().then((idArray) => { + console.log('queryActivatedOsAccountIds, idArray: ' + idArray); + }).catch((err) => { + console.log('queryActivatedOsAccountIds err: ' + JSON.stringify(err)); + }); + ``` + +### queryCurrentOsAccount(deprecated) + +queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void + +Obtains information about the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCurrentOsAccount](#getcurrentosaccount9). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account information obtained. Otherwise, **data** is an error object.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.queryCurrentOsAccount((err, curAccountInfo)=>{ + console.log('queryCurrentOsAccount err:' + JSON.stringify(err)); + console.log('queryCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); + }); + ``` + +### queryCurrentOsAccount(deprecated) + +queryCurrentOsAccount(): Promise<OsAccountInfo> + +Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getCurrentOsAccount](#getcurrentosaccount9-1). + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| ---------------------------------------------- | ------------------------------------------ | +| Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account information obtained.| + +**Example** + + ```js + let accountManager = account_osAccount.getAccountManager(); + accountManager.queryCurrentOsAccount().then((accountInfo) => { + console.log('queryCurrentOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); }).catch((err) => { - console.log('getSerialNumberByOsAccountLocalId err: ' + JSON.stringify(err)); + console.log('queryCurrentOsAccount err: ' + JSON.stringify(err)); }); ``` -### on - -on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void +### getOsAccountTypeFromProcess(deprecated) -Subscribes to OS account changes. This API uses an asynchronous callback to return the result. +getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void -This is a system API and cannot be called by third-party applications. +Obtains the type of the account to which the current process belongs. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountType](#getosaccounttype9). **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------------------------------------------------ | -| type | 'activate' \| 'activating' | Yes | Type of the event to subscribe to. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| -| name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes. | -| callback | Callback<number> | Yes | Callback used to return the OS account ID and status changes. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<[OsAccountType](#osaccounttype)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account type obtained. Otherwise, **err** is an error object.| **Example** ```js let accountManager = account_osAccount.getAccountManager(); - function onCallback(receiveLocalId){ - console.log('receive localId:' + receiveLocalId); - } - accountManager.on('activating', 'osAccountOnOffNameA', onCallback); + accountManager.getOsAccountTypeFromProcess((err, accountType) => { + console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); + console.log('getOsAccountTypeFromProcess accountType: ' + accountType); + }); ``` -### off - -off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void +### getOsAccountTypeFromProcess(deprecated) -Unsubscribes from the OS account changes. This API uses an asynchronous callback to return the result. +getOsAccountTypeFromProcess(): Promise<OsAccountType> -This is a system API and cannot be called by third-party applications. +Obtains the type of the account to which the current process belongs. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountType](#getosaccounttype9-1). **System capability**: SystemCapability.Account.OsAccount -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------------------------------------------------ | -| type | 'activate' \| 'activating' | Yes | Type of the event to unsubscribe from. The value **activate** means an event indicating that an OS account is activated, and **activating** means an event indicating that an OS account is being activated.| -| name | string | Yes | Subscription name, which can be customized. The value cannot be empty or exceed 1024 bytes, and must be the same as the value passed by **on()**.| -| callback | Callback<number> | No | Callback used to return the OS account changes. By default, **0** is returned. | +| Type | Description | +| ---------------------------------------------- | ----------------------------------------------- | +| Promise<[OsAccountType](#osaccounttype)> | Promise used to return the OS account type obtained.| **Example** ```js let accountManager = account_osAccount.getAccountManager(); - function offCallback(){ - console.log('off enter') - } - accountManager.off('activating', 'osAccountOnOffNameA', offCallback); + accountManager.getOsAccountTypeFromProcess().then((accountType) => { + console.log('getOsAccountTypeFromProcess, accountType: ' + accountType); + }).catch((err) => { + console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); + }); ``` -### getBundleIdFromUid9+ +### getDistributedVirtualDeviceId(deprecated) -getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; +getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void -Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. +Obtains the ID of the distributed virtual device. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryDistributedVirtualDeviceId](#querydistributedvirtualdeviceid9). -This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------------------------------------------------ | -| uid | number | Yes | Process UID.| -| callback | AsyncCallback<number> | Yes | Callback invoked to return the bundle ID obtained. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------------------------- | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the distributed virtual device ID obtained. Otherwise, **data** is an error object.| **Example** ```js let accountManager = account_osAccount.getAccountManager(); - let testUid = 1000000; - accountManager.getBundleIdFromUid(testUid, (err, bundleId) => { - console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err)); - console.info('getBundleIdFromUid bundleId:' + JSON.stringify(bundleId)); + accountManager.getDistributedVirtualDeviceId((err, virtualID) => { + console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); + console.log('getDistributedVirtualDeviceId virtualID: ' + virtualID); }); ``` -### getBundleIdFromUid9+ -getBundleIdFromUid(uid: number): Promise<number>; +### getDistributedVirtualDeviceId(deprecated) -Obtains the bundle ID based on the UID. This API uses a promise to return the result. +getDistributedVirtualDeviceId(): Promise<string> -This is a system API and cannot be called by third-party applications. +Obtains the ID of the distributed virtual device. This API uses a promise to return the result. -**System capability**: SystemCapability.Account.OsAccount +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryDistributedVirtualDeviceId](#querydistributedvirtualdeviceid9-1). -**Parameters** +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------ | -| uid | number | Yes | Process UID.| +**System capability**: SystemCapability.Account.OsAccount **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<number> | Promise used to return the bundle ID obtained.| +| Type | Description | +| --------------------- | --------------------------------- | +| Promise<string> | Promise used to return the distributed virtual device ID obtained.| **Example** ```js let accountManager = account_osAccount.getAccountManager(); - let testUid = 1000000; - accountManager.getBundleIdFromUid(testUid).then((result) => { - console.info('getBundleIdFromUid bundleId:' + JSON.stringify(result)); - }).catch((err)=>{ - console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err)); + accountManager.getDistributedVirtualDeviceId().then((virtualID) => { + console.log('getDistributedVirtualDeviceId, virtualID: ' + virtualID); + }).catch((err) => { + console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); }); ``` -### isMainOsAccount9+ - -isMainOsAccount(callback: AsyncCallback<boolean>): void; +### getOsAccountLocalIdBySerialNumber(deprecated) -Checks whether the current process belongs to the main OS account. This API uses an asynchronous callback to return the result. +getOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void -This is a system API and cannot be called by third-party applications. +Obtains the OS account ID based on the SN. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdBySerialNumber](#queryosaccountlocalidbyserialnumber9). **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the current process belongs to the main OS account, **true** will be returned. Otherwise, **false** will be returned. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------- | ---- | -------------------------------------------------------------------------------- | +| serialNumber | number | Yes | Account SN. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the OS account ID obtained. Otherwise, **err** is an error object.| -**Example** +**Example**: Obtain the ID of the OS account whose SN is 12345. ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isMainOsAccount((err,result)=>{ - console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); - console.info('isMainOsAccount result:' + JSON.stringify(result)); + let serialNumber = 12345; + accountManager.getOsAccountLocalIdBySerialNumber(serialNumber, (err, localId)=>{ + console.log('ger localId err:' + JSON.stringify(err)); + console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); }); ``` -### isMainOsAccount9+ -isMainOsAccount(): Promise<boolean>; +### getOsAccountLocalIdBySerialNumber(deprecated) -Checks whether the current process belongs to the main OS account. This API uses a promise to return the result. +getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> -This is a system API and cannot be called by third-party applications. +Obtains the OS account ID based on the SN. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdBySerialNumber](#queryosaccountlocalidbyserialnumber9-1). **System capability**: SystemCapability.Account.OsAccount +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | ---------- | +| serialNumber | number | Yes | Account SN.| + **Return value** | Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. If the current process belongs to the main OS account, **true** will be returned. Otherwise, **false** will be returned.| +| --------------------- | -------------------------------------------- | +| Promise<number> | Promise used to return the OS account ID obtained.| -**Example** +**Example**: Obtain the ID of the OS account whose SN is 12345. ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.isMainOsAccount().then((result) => { - console.info('isMainOsAccount result:' + JSON.stringify(result)); - }).catch((err)=>{ - console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); + let serialNumber = 12345; + accountManager.getOsAccountLocalIdBySerialNumber(serialNumber).then((localId) => { + console.log('getOsAccountLocalIdBySerialNumber localId: ' + localId); + }).catch((err) => { + console.log('getOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err)); }); ``` -### queryOsAccountConstraintSourceTypes9+ -queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; +### getSerialNumberByOsAccountLocalId(deprecated) -Obtains the constraint source information of an OS account. This API uses an asynchronous callback to return the result. +getSerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void -This is a system API and cannot be called by third-party applications. +Obtains the SN of an OS account based on the account ID. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [querySerialNumberByOsAccountLocalId](#queryserialnumberbyosaccountlocalid9). **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------------------------------------------------ | -| localId | number | Yes | ID of the target OS account.| -| constraint | string | Yes | Name of the [constraint](#constraints) to query.| -| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback invoked to return the source information about the specified [constraint](#constraints). | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the SN obtained. Otherwise, **err** is an error object.| -**Example** +**Example**: Obtain the SN of the OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi',(err,sourceTypeInfos)=>{ - console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err)); - console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(sourceTypeInfos)); + let localId = 100; + accountManager.getSerialNumberByOsAccountLocalId(localId, (err, serialNumber)=>{ + console.log('ger serialNumber err:' + JSON.stringify(err)); + console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); }); ``` -### queryOsAccountConstraintSourceTypes9+ - -queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>; +### getSerialNumberByOsAccountLocalId(deprecated) -Obtains the constraint source information of an OS account. This API uses a promise to return the result. +getSerialNumberByOsAccountLocalId(localId: number): Promise<number> -This is a system API and cannot be called by third-party applications. +Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [querySerialNumberByOsAccountLocalId](#queryserialnumberbyosaccountlocalid9-1). **System capability**: SystemCapability.Account.OsAccount **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------ | -| localId | number | Yes | ID of the target OS account.| -| constraint | string | Yes | Name of the [constraint](#constraints) to query.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------- | +| localId | number | Yes | ID of the target OS account.| **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint](#constraints).| +| Type | Description | +| --------------------- | -------------------------------------- | +| Promise<number> | Promise used to return the SN obtained.| -**Example** +**Example**: Obtain the SN of the OS account 100. ```js let accountManager = account_osAccount.getAccountManager(); - accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi').then((result) => { - console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(result)); - }).catch((err)=>{ - console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err)); + let localId = 100; + accountManager.getSerialNumberByOsAccountLocalId(localId).then((serialNumber) => { + console.log('getSerialNumberByOsAccountLocalId serialNumber: ' + serialNumber); + }).catch((err) => { + console.log('getSerialNumberByOsAccountLocalId err: ' + JSON.stringify(err)); }); ``` @@ -1927,7 +3796,7 @@ This is a system API and cannot be called by third-party applications. Provides APIs for user authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. ### constructor8+ @@ -1935,7 +3804,7 @@ constructor() A constructor used to create an instance for user authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -1944,14 +3813,13 @@ This is a system API and cannot be called by third-party applications. let userAuth = new account_osAccount.UserAuth(); ``` - ### getVersion8+ getVersion(): number; Obtains version information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -1972,9 +3840,9 @@ This is a system API and cannot be called by third-party applications. getAvailableStatus(authType: AuthType, authTrustLevel: AuthTrustLevel): number; -Checks whether the identity authentication feature is available. +Obtains the available status of the authentication capability corresponding to the specified authentication type and trust level. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -1982,24 +3850,35 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | -----------------------------------------------| ---- | ------------------------- | +| Name | Type | Mandatory| Description | +| --------------- | -----------------------------------| ---- | ------------------------- | | authType | [AuthType](#authtype8) | Yes | Authentication credential type. | -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result.| +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication.| **Return value** -| Type | Description | -| :----- | :---------------------------------------- | -| number | [Result code](#resultcode8).| +| Type | Description | +| ------ | ----------------------------- | +| number | Available status of the authentication capability.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid authType or authTrustLevel. | **Example** ```js let userAuth = new account_osAccount.UserAuth(); let authType = account_osAccount.AuthType.PIN; let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; - let status = userAuth.getAvailableStatus(authType, authTrustLevel); - console.log('getAvailableStatus status = ' + status); + try { + let status = userAuth.getAvailableStatus(authType, authTrustLevel); + console.log('getAvailableStatus status = ' + status); + } catch (e) { + console.log('getAvailableStatus exception = ' + JSON.stringify(e)); + } ``` ### getProperty8+ @@ -2008,7 +3887,7 @@ getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProp Obtains the executor property based on the request. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2017,9 +3896,16 @@ This is a system API and cannot be called by third-party applications. **Parameters** | Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------------------- | ---- | ---------------------------------- | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------ | | request | [GetPropertyRequest](#getpropertyrequest8) | Yes | Request information, including the authentication credential type and property list.| -| callback | AsyncCallback<[ExecutorProperty](#executorproperty8)> | Yes | Callback invoked to return the executor property obtained. | +| callback | AsyncCallback<[ExecutorProperty](#executorproperty8)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the executor property information obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | **Example** ```js @@ -2033,10 +3919,14 @@ This is a system API and cannot be called by third-party applications. authType: account_osAccount.AuthType.PIN, keys: keys }; - userAuth.getProperty(request, (err, result) => { - console.log('getProperty err = ' + JSON.stringify(err)); - console.log('getProperty result = ' + JSON.stringify(result)); - }); + try { + userAuth.getProperty(request, (err, result) => { + console.log('getProperty err = ' + JSON.stringify(err)); + console.log('getProperty result = ' + JSON.stringify(result)); + }); + } catch (e) { + console.log('getProperty exception = ' + JSON.stringify(e)); + } ``` ### getProperty8+ @@ -2045,7 +3935,7 @@ getProperty(request: GetPropertyRequest): Promise<ExecutorProperty>; Obtains the executor property based on the request. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2061,7 +3951,14 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | :---------------------------------------------------------------- | :-------------------------------------------------- | -| Promise<[ExecutorProperty](#executorproperty8)> | Promise used to return the executor property obtained.| +| Promise<[ExecutorProperty](#executorproperty8)> | Promise used to return the executor property information obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | **Example** ```js @@ -2075,11 +3972,15 @@ This is a system API and cannot be called by third-party applications. authType: account_osAccount.AuthType.PIN, keys: keys }; - userAuth.getProperty(request).then((result) => { - console.log('getProperty result = ' + JSON.stringify(result)); - }).catch((err) => { - console.log('getProperty error = ' + JSON.stringify(err)); - }); + try { + userAuth.getProperty(request).then((result) => { + console.log('getProperty result = ' + JSON.stringify(result)); + }).catch((err) => { + console.log('getProperty error = ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('getProperty exception = ' + JSON.stringify(e)); + } ``` ### setProperty8+ @@ -2088,7 +3989,7 @@ setProperty(request: SetPropertyRequest, callback: AsyncCallback<number>): Sets the property for the initialization algorithm. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2098,8 +3999,15 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------- | -| request | [SetPropertyRequest](#setpropertyrequest8)| Yes | Request information, including the authentication credential type and key value to set. | -| callback | AsyncCallback<number> | Yes | Callback invoked to return the [result](#resultcode8).| +| request | [SetPropertyRequest](#setpropertyrequest8)| Yes | Request information, including the authentication credential type and the key value to set. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a [result code](#resultcode8). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | **Example** ```js @@ -2109,10 +4017,14 @@ This is a system API and cannot be called by third-party applications. key: account_osAccount.SetPropertyType.INIT_ALGORITHM, setInfo: new Uint8Array([0]) }; - userAuth.setProperty(request, (err, result) => { - console.log('setProperty error = ' + JSON.stringify(err)); - console.log('setProperty result = ' + JSON.stringify(result)); - }); + try { + userAuth.setProperty(request, (err, result) => { + console.log('setProperty error = ' + JSON.stringify(err)); + console.log('setProperty result = ' + JSON.stringify(result)); + }); + } catch (e) { + console.log('setProperty exception = ' + JSON.stringify(e)); + } ``` ### setProperty8+ @@ -2121,7 +4033,7 @@ setProperty(request: SetPropertyRequest): Promise<number>; Sets the property for the initialization algorithm. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2129,15 +4041,22 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ---------------------------------------- | | request | [SetPropertyRequest](#setpropertyrequest8) | Yes | Request information, including the authentication credential type and the key value to set.| **Return value** -| Type | Description | -| :-------------------- | :-------------------------------------------------------------------------------------------- | -| Promise<number> | Promise used to return the [result](#resultcode8).| +| Type | Description | +| :-------------------- | :------------------------------------------------------------ | +| Promise<number> | Promise used to return the [result code](#resultcode8).| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid request. | **Example** ```js @@ -2147,20 +4066,24 @@ This is a system API and cannot be called by third-party applications. key: account_osAccount.SetPropertyType.INIT_ALGORITHM, setInfo: new Uint8Array([0]) }; - userAuth.setProperty(request).then((result) => { - console.log('setProperty result = ' + JSON.stringify(result)); - }).catch((err) => { - console.log('setProperty error = ' + JSON.stringify(err)); - }); + try { + userAuth.setProperty(request).then((result) => { + console.log('setProperty result = ' + JSON.stringify(result)); + }).catch((err) => { + console.log('setProperty error = ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('setProperty exception = ' + JSON.stringify(e)); + } ``` ### auth8+ auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; -Performs authentication. This API uses a callback to return the result. +Performs authentication for the current user. This API uses a callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2168,41 +4091,57 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | ---------------------------------------------------- | --- | ------------------------------------ | -| challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security.| +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------- | --- | ------------------------------------ | +| challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security.| | authType | [AuthType](#authtype8) | Yes | Authentication credential type. | | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | -| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result and obtained information. | - +| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result. | **Return value** | Type | Description | -| :--------- | :----------------- | +| ---------- | ------------------ | | Uint8Array | ID of the context for canceling the authentication.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid challenge or authType or authTrustLevel. | +| 12300101 | Credential is incorrect. | +| 12300105 | Unsupported authTrustLevel. | +| 12300106 | Unsupported authType. | +| 12300110 | Authentication locked. | +| 12300111 | Authentication timeout. | +| 12300112 | Authentication service busy. | + **Example** ```js let userAuth = new account_osAccount.UserAuth(); let challenge = new Uint8Array([0]); let authType = account_osAccount.AuthType.PIN; let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; - userAuth.auth(challenge, authType, authTrustLevel, { - onResult: function(result,extraInfo){ - console.log('auth result = ' + result); - console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); - } - }); + try { + userAuth.auth(challenge, authType, authTrustLevel, { + onResult: function(result,extraInfo){ + console.log('auth result = ' + result); + console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); + } + }); + } catch (e) { + console.log('auth exception = ' + JSON.stringify(e)); + } ``` ### authUser8+ authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; -Perform user authentication. This API uses a callback to return the result. +Performs authentication for a user. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2216,15 +4155,27 @@ This is a system API and cannot be called by third-party applications. | challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security. | | authType | [AuthType](#authtype8) | Yes | Authentication credential type. | | authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | -| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result and obtained information. | - +| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result. | **Return value** | Type | Description | -| :--------- | :----------------- | +| ---------- | ------------------ | | Uint8Array | ID of the context for canceling the authentication.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid userId or challenge or authType or authTrustLevel. | +| 12300101 | Credential is incorrect. | +| 12300105 | Unsupported authTrustLevel. | +| 12300106 | Unsupported authType. | +| 12300110 | Authentication locked. | +| 12300111 | Authentication timeout. | +| 12300112 | Authentication service busy. | + **Example** ```js let userAuth = new account_osAccount.UserAuth(); @@ -2232,21 +4183,25 @@ This is a system API and cannot be called by third-party applications. let challenge = new Uint8Array([0]); let authType = account_osAccount.AuthType.PIN; let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; - userAuth.authUser(userID, challenge, authType, authTrustLevel, { - onResult: function(result,extraInfo){ + try { + userAuth.authUser(userID, challenge, authType, authTrustLevel, { + onResult: function(result,extraInfo){ console.log('authUser result = ' + result); console.log('authUser extraInfo = ' + JSON.stringify(extraInfo)); - } - }); + } + }); + } catch (e) { + console.log('authUser exception = ' + JSON.stringify(e)); + } ``` ### cancelAuth8+ -cancelAuth(contextID: Uint8Array): number; +cancelAuth(contextID: Uint8Array): void; -Cancels authentication. +Cancels an authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2256,34 +4211,38 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory | Description | | ----------| ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | Yes | ID of the authentication context. The context ID is dynamically generated.| +| contextId | Uint8Array | Yes | ID of the authentication context. The context ID is dynamically generated.| -**Return value** +**Error codes** -| Type | Description | -| :----- | :-------------------------------------------------------- | -| number | [Result code](#resultcode8).| +| ID| Error Message | +| -------- | ------------------ | +| 12300001 | System service exception. | +| 12300002 | Invalid contextId. | **Example** ```js let userAuth = new account_osAccount.UserAuth(); let pinAuth = new account_osAccount.PINAuth(); let challenge = new Uint8Array([0]); - let contextID = userAuth.auth(challenge, account_osAccount.AuthType.PIN, account_osAccount.AuthTrustLevel.ATL1, { + let contextId = userAuth.auth(challenge, account_osAccount.AuthType.PIN, account_osAccount.AuthTrustLevel.ATL1, { onResult: (result, extraInfo) => { console.log('auth result = ' + result); console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); } }); - let result = userAuth.cancelAuth(contextID); - console.log('cancelAuth result = ' + result); + try { + userAuth.cancelAuth(contextId); + } catch (e) { + console.log('cancelAuth exception = ' + JSON.stringify(e)); + } ``` ## PINAuth8+ Provides APIs for PIN authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. ### constructor8+ @@ -2291,7 +4250,7 @@ constructor() A constructor used to create an instance for PIN authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2300,13 +4259,13 @@ This is a system API and cannot be called by third-party applications. let pinAuth = new account_osAccount.PINAuth(); ``` -### registerInputer +### registerInputer8+ -registerInputer(inputer: IInputer): boolean; +registerInputer(inputer: IInputer): void; -Registers an inputer. +Register a PIN inputer. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2314,9 +4273,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ----------| ----------------------------------- | --- | ------------------ | -| inputer | [IInputer](#iinputer8) | Yes | Callback invoked to obtain the PIN.| +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| inputer | [IInputer](#iinputer8) | Yes | PIN inputer, which is used to obtain the PIN.| **Return value** @@ -2324,25 +4283,36 @@ This is a system API and cannot be called by third-party applications. | :------ | :-------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300103 | Inputer already registered. | + **Example** ```js let pinAuth = new account_osAccount.PINAuth(); let password = new Uint8Array([0, 0, 0, 0, 0]); - let result = pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); - } - }); - console.log('registerInputer result = ' + result); + try { + let result = pinAuth.registerInputer({ + onGetData: (pinSubType, callback) => { + callback.onSetData(pinSubType, password); + } + }); + console.log('registerInputer result = ' + result); + } catch (e) { + console.log('registerInputer exception = ' + JSON.stringify(e)); + } ``` -### unregisterInputer +### unregisterInputer8+ unregisterInputer(): void; -Unregisters the inputer. +Unregisters this PIN inputer. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2356,17 +4326,17 @@ This is a system API and cannot be called by third-party applications. ## UserIdentityManager8+ -Provides APIs for user identity management. +Provides APIs for user identity management (IDM). -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. ### constructor8+ constructor() -A constructor used to create an instance for user authentication. +A constructor used to create an instance for user IDM. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2379,9 +4349,9 @@ This is a system API and cannot be called by third-party applications. openSession(callback: AsyncCallback<Uint8Array>): void; -Opens a session to start identity management (IDM) so that a challenge value can be obtained. This API uses an asynchronous callback to return the result. +Opens a session to obtain the challenge value. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2389,26 +4359,36 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<Uint8Array> | Yes | Callback invoked to return the challenge value. If **0** is returned, the operation failed.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | -------------------------------------------------------------- | +| callback | AsyncCallback<Uint8Array> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the challenge value obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); - userIDM.openSession((err, challenge) => { - console.log('openSession error = ' + JSON.stringify(err)); - console.log('openSession challenge = ' + JSON.stringify(challenge)); - }); + try { + userIDM.openSession((err, challenge) => { + console.log('openSession error = ' + JSON.stringify(err)); + console.log('openSession challenge = ' + JSON.stringify(challenge)); + }); + } catch (e) { + console.log('openSession exception = ' + JSON.stringify(e)); + } ``` ### openSession8+ openSession(): Promise<Uint8Array>; -Opens a session to start IDM so that a challenge value can be obtained. This API uses a promise to return the result. +Opens a session to obtain the challenge value. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2416,27 +4396,37 @@ This is a system API and cannot be called by third-party applications. **Return value** -| Type | Description | -| :------------------------ | :------------------------------------------------------- | -| Promise<Uint8Array> | Promise used to return the challenge value. If **0** is returned, the operation failed.| +| Type | Description | +| :------------------------ | ----------------------- | +| Promise<Uint8Array> | Promise used to return the challenge value obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); - userIDM.openSession().then((challenge) => { - console.info('openSession challenge = ' + JSON.stringify(challenge)); - }).catch((err) => { - console.info('openSession error = ' + JSON.stringify(err)); - }); + try { + userIDM.openSession().then((challenge) => { + console.info('openSession challenge = ' + JSON.stringify(challenge)); + }).catch((err) => { + console.info('openSession error = ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('openSession exception = ' + JSON.stringify(e)); + } ``` ### addCredential8+ addCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; -Adds credential information, which includes the authentication credential type, subtype, and token (if a non-PIN credential is added). This API uses a callback to return the result. +Adds credential information, including the credential type, subtype, and token (if a non-PIN credential is added). -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2444,10 +4434,19 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | ------------------------------------------------ | --- | -------------------------------- | -| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | Credential information to add. | -| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result and obtained information. | +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------ | --- | ---------------------------- | +| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | Credential information to add. | +| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid credentialInfo, i.e. authType or authSubType. | +| 12300101 | Token is invalid. | +| 12300106 | Unsupported authType. | **Example** ```js @@ -2465,12 +4464,16 @@ This is a system API and cannot be called by third-party applications. }; let userIDM = new account_osAccount.UserIdentityManager(); userIDM.openSession((err, challenge) => { + try { userIDM.addCredential(credentialInfo, { onResult: (result, extraInfo) => { console.log('updateCredential result = ' + result); console.log('updateCredential extraInfo = ' + extraInfo); } }); + } catch (e) { + console.log('updateCredential exception = ' + JSON.stringify(e)); + } }); ``` @@ -2480,7 +4483,7 @@ updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; Updates credential information. This API uses a callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2488,10 +4491,19 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | ------------------------------------------------- | --- | -------------------------------- | +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------- | --- | ------------------------- | | credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | New credential information. | -| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result and obtained information. | +| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the new credential information.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid credentialInfo, i.e. authType or authSubType or token. | +| 12300101 | Token is invalid. | +| 12300106 | Unsupported authType. | **Example** ```js @@ -2516,12 +4528,16 @@ This is a system API and cannot be called by third-party applications. return; } credentialInfo.token = extraInfo.token; - userIDM.updateCredential(credentialInfo, { - onResult: (result, extraInfo) => { - console.log('updateCredential result = ' + result); - console.log('updateCredential extraInfo = ' + extraInfo); - } - }); + try { + userIDM.updateCredential(credentialInfo, { + onResult: (result, extraInfo) => { + console.log('updateCredential result = ' + result); + console.log('updateCredential extraInfo = ' + extraInfo); + } + }); + } catch (e) { + console.log('updateCredential exception = ' + JSON.stringify(e)); + } } }); }); @@ -2533,7 +4549,7 @@ closeSession(): void; Closes this session to terminate IDM. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2547,11 +4563,11 @@ This is a system API and cannot be called by third-party applications. ### cancel8+ -cancel(challenge: Uint8Array): number; +cancel(challenge: Uint8Array): void; Cancels an entry based on the challenge value. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2563,27 +4579,31 @@ This is a system API and cannot be called by third-party applications. | -------- | ----------- | ---- | ----- | | challenge | Uint8Array | Yes | Challenge value.| -**Return value** +**Error codes** -| Type | Description | -| :----- | :-------------------------------------------------------- | -| number | [Result code](#resultcode8).| +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid challenge. | **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); let challenge = new Uint8Array([0]); - let result = userIDM.cancel(challenge); - console.log('cancel result: ' + result); + try { + userIDM.cancel(challenge); + } catch(err) { + console.log("cancel err:" + JSON.stringify(err)); + } ``` ### delUser8+ delUser(token: Uint8Array, callback: IIdmCallback): void; -Deletes a user based on the authentication token. The API uses a callback to return the result. +Deletes a user based on the authentication token. This API uses a callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2591,30 +4611,41 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------ | --- | ------------------------- | -| token | Uint8Array | Yes | Authentication token. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | --- | ------------------------- | +| token | Uint8Array | Yes | Authentication token. | | callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300101 | Token is invalid. | + **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); let token = new Uint8Array([0]); - userIDM.delUser(token, { - onResult: (result, extraInfo) => { - console.log('delUser result = ' + result); - console.log('delUser extraInfo = ' + JSON.stringify(extraInfo)); - } - }); + try { + userIDM.delUser(token, { + onResult: (result, extraInfo) => { + console.log('delUser result = ' + result); + console.log('delUser extraInfo = ' + JSON.stringify(extraInfo)); + } + }); + } catch (e) { + console.log('delUser exception = ' + JSON.stringify(e)); + } ``` ### delCred8+ delCred(credentialId: Uint8Array, token: Uint8Array, callback: IIdmCallback): void; -Deletes user credential information. The API uses a callback to return the result. +Deletes user credential information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2623,31 +4654,44 @@ This is a system API and cannot be called by third-party applications. **Parameters** | Name | Type | Mandatory| Description | -| --------------- | ----------------------------------------------- | --- | ---------------------------| -| credentialId | Uint8Array | Yes | Credential ID. | -| token | Uint8Array | Yes | Authentication token. | +| --------------- | ----------------------------------- | --- | ---------------------------| +| credentialId | Uint8Array | Yes | Credential ID. | +| token | Uint8Array | Yes | Authentication token. | | callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid credentialId. | +| 12300101 | Token is invalid. | +| 12300102 | Credential not found. | + **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); let credentialId = new Uint8Array([0]); let token = new Uint8Array([0]); - userIDM.delCred(credentialId, token, { - onResult: (result, extraInfo) => { - console.log('delCred result = ' + result); - console.log('delCred extraInfo = ' + JSON.stringify(extraInfo)); - } - }); + try { + userIDM.delCred(credentialId, token, { + onResult: (result, extraInfo) => { + console.log('delCred result = ' + result); + console.log('delCred extraInfo = ' + JSON.stringify(extraInfo)); + } + }); + } catch (e) { + console.log('delCred exception = ' + JSON.stringify(e)); + } ``` ### getAuthInfo8+ getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>): void; -Obtains authentication information. This API uses asynchronous callback to return the result. +Obtains authentication information. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2655,18 +4699,28 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------------- | ---- | -------------------------------------------------- | -| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return information about all the user's enrolled credentials of the specified type.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------------------ | ---- | --------------------------------------------- | +| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential information obtained. Otherwise, **err** is an error object.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------- | +| 12300001 | System service exception. | +| 12300102 | Credential not found. | **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); - userIDM.getAuthInfo((err, result) => { - console.log('getAuthInfo err = ' + JSON.stringify(err)); - console.log('getAuthInfo result = ' + JSON.stringify(result)); - }); + try { + userIDM.getAuthInfo((err, result) => { + console.log('getAuthInfo err = ' + JSON.stringify(err)); + console.log('getAuthInfo result = ' + JSON.stringify(result)); + }); + } catch (e) { + console.log('getAuthInfo exception = ' + JSON.stringify(e)); + } ``` ### getAuthInfo8+ @@ -2675,7 +4729,7 @@ getAuthInfo(authType: AuthType, callback: AsyncCallback<Array<EnrolledCred Obtains authentication information of the specified type. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2686,24 +4740,36 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | -------------------------------------------------- | | authType | [AuthType](#authtype8) | Yes | Authentication credential type. | -| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return information about all the user's enrolled credentials of the specified type.| +| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the information about all enrolled credentials of the specified type. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid authType. | +| 12300102 | Credential not found. | **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); - userIDM.getAuthInfo(account_osAccount.AuthType.PIN, (err, result) => { - console.log('getAuthInfo err = ' + JSON.stringify(err)); - console.log('getAuthInfo result = ' + JSON.stringify(result)); - }); + try { + userIDM.getAuthInfo(account_osAccount.AuthType.PIN, (err, result) => { + console.log('getAuthInfo err = ' + JSON.stringify(err)); + console.log('getAuthInfo result = ' + JSON.stringify(result)); + }); + } catch (e) { + console.log('getAuthInfo exception = ' + JSON.stringify(e)); + } ``` ### getAuthInfo8+ getAuthInfo(authType?: AuthType): Promise<Array<EnrolledCredInfo>>; -Obtains authentication information. This API uses a promise to return the result. +Obtains authentication information of the specified type. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2713,37 +4779,49 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | -------- | -| authType | [AuthType](#authtype8) | No | Authentication credential type.| +| authType | [AuthType](#authtype8) | No | Authentication credential type.| **Return value** -| Type | Description | -| :------------------------------------------- | :------------------------------------------------------------------------ | -| Promise<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Promise used to return information about all the user's enrolled credentials of the specified type.| +| Type | Description | +| :------------------------------------------- | :----------------------------------------------------------------------- | +| Promise<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Promise used to return the information about all the enrolled credentials of the specified type.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid authType. | +| 12300102 | Credential not found. | **Example** ```js let userIDM = new account_osAccount.UserIdentityManager(); - userIDM.getAuthInfo(account_osAccount.AuthType.PIN).then((result) => { - console.log('getAuthInfo result = ' + JSON.stringify(result)) - }).catch((err) => { - console.log('getAuthInfo error = ' + JSON.stringify(err)); - }); + try { + userIDM.getAuthInfo(account_osAccount.AuthType.PIN).then((result) => { + console.log('getAuthInfo result = ' + JSON.stringify(result)) + }).catch((err) => { + console.log('getAuthInfo error = ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('getAuthInfo exception = ' + JSON.stringify(e)); + } ``` ## IInputData8+ Provides callbacks for PIN operations. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. ### onSetData8+ onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. -Called to set data. +Called to set data in a PIN operation. **System capability**: SystemCapability.Account.OsAccount @@ -2751,7 +4829,7 @@ Called to set data. | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | -| pinSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | +| pinSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | | data | Uint8Array | Yes | Data (credential) to set. The data is used for authentication and operations for adding and modifying credentials.| **Example** @@ -2773,7 +4851,7 @@ Called to set data. Provides callbacks for the PIN input box. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. ### onGetData8+ @@ -2781,7 +4859,7 @@ onGetData: (pinSubType: AuthSubType, callback: IInputData) => void; Called to obtain data. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2813,15 +4891,15 @@ This is a system API and cannot be called by third-party applications. Provides callbacks for user authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. ### onResult8+ onResult: (result: number, extraInfo: AuthResult) => void; -Called to return the authentication result code. +Called to return the result code and authentication result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2846,9 +4924,9 @@ This is a system API and cannot be called by third-party applications. onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; -Called to return the **TipsCode** during the authentication process. +Called to acquire identity authentication information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2879,15 +4957,15 @@ This is a system API and cannot be called by third-party applications. Provides callbacks for IDM. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. ### onResult8+ onResult: (result: number, extraInfo: RequestResult) => void; -Called to return the authentication result code. +Called to return the result code and request result information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2912,9 +4990,9 @@ This is a system API and cannot be called by third-party applications. onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; -Called to return the **TipsCode** during the authentication process. +Called to acquire IDM information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2945,7 +5023,7 @@ This is a system API and cannot be called by third-party applications. Defines the request for obtaining property information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2958,7 +5036,7 @@ This is a system API and cannot be called by third-party applications. Defines the request for setting property information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2972,7 +5050,7 @@ This is a system API and cannot be called by third-party applications. Defines the executor property. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -2987,7 +5065,7 @@ This is a system API and cannot be called by third-party applications. Defines the authentication result information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3001,7 +5079,7 @@ This is a system API and cannot be called by third-party applications. Defines the credential information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3009,13 +5087,13 @@ This is a system API and cannot be called by third-party applications. | ------------ | ---------------------------------------- | ----- | ----------------- | | credType | [AuthType](#authtype8) | Yes | Authentication credential type. | | credSubType | [AuthSubType](#authsubtype8) | Yes | Authentication credential subtype. | -| token | Uint8Array | Yes | Authentication token. | +| token | Uint8Array | Yes | Authentication token. | ## RequestResult8+ Defines the request result information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3027,7 +5105,7 @@ This is a system API and cannot be called by third-party applications. Defines enrolled credential information. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3040,9 +5118,9 @@ This is a system API and cannot be called by third-party applications. ## GetPropertyType8+ -Enumerates the types of the properties to obtain. +Enumerates the types of properties to obtain. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3054,9 +5132,9 @@ This is a system API and cannot be called by third-party applications. ## SetPropertyType8+ -Enumerates the types of the properties to set. +Enumerates the types of properties to set. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3068,7 +5146,7 @@ This is a system API and cannot be called by third-party applications. Enumerates the authentication credential types. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3081,7 +5159,7 @@ This is a system API and cannot be called by third-party applications. Enumerates the authentication credential subtypes. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3097,7 +5175,7 @@ This is a system API and cannot be called by third-party applications. Enumerates the trust levels of the authentication result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3112,19 +5190,19 @@ This is a system API and cannot be called by third-party applications. Enumerates the modules from which information is obtained. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | | --------- | ------ | ------------------------ | -| FACE_AUTH | 1 | Face authentication module.| +| FACE_AUTH | 1 | Facial authentication module.| ## ResultCode8+ Enumerates the authentication result codes. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3146,7 +5224,7 @@ This is a system API and cannot be called by third-party applications. Enumerates the tip codes for facial authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3168,7 +5246,7 @@ This is a system API and cannot be called by third-party applications. Enumerates the tip codes for fingerprint authentication. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3183,7 +5261,7 @@ This is a system API and cannot be called by third-party applications. ## OsAccountInfo -Defines information about an OS account. +Defines the OS account information. **System capability**: SystemCapability.Account.OsAccount @@ -3205,7 +5283,7 @@ Defines information about an OS account. ## DomainAccountInfo8+ -Domain account information. +Defines the domain account information. **System capability**: SystemCapability.Account.OsAccount @@ -3284,9 +5362,9 @@ Domain account information. ## ConstraintSourceTypeInfo9+ -Defines information about the source of a constraint. +Defines the constraint source type. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3299,7 +5377,7 @@ This is a system API. Enumerates the constraint sources. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Account.OsAccount @@ -3309,3 +5387,4 @@ This is a system API. | CONSTRAINT_TYPE_BASE | 1 | Constraint from system settings. | | CONSTRAINT_TYPE_DEVICE_OWNER | 2 | Constraint from the device owners' settings. | | CONSTRAINT_TYPE_PROFILE_OWNER | 3 | Constraint from the profile owners' settings. | + diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index 00802493ea68efd037b17e0712d78b755d131059..be28e4b7590f1671660228d3e78f2e822451a847 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -1,149 +1,214 @@ # Pasteboard -The **pasteboard** module provides the pasteboard management client and pasteboard server. The pasteboard management client manages pasteboard APIs. Specifically, it provides pasteboard APIs in JavaScript for applications, creates pasteboard data on the application framework side, and requests the pasteboard SA to create, delete, query, convert text, and configure pasteboards. The pasteboard server manages pasteboard events as well as the pasteboard SA lifecycle, providing support for the copy and paste functions of the system. +The **pasteboard** module provides the copy and paste support for the system pasteboard. You can use the APIs of this module to operate pasteboard content of the plain text, HTML, URI, Want, pixel map, and other types. > **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 - -``` +```js import pasteboard from '@ohos.pasteboard'; ``` - ## Attributes **System capability**: SystemCapability.MiscServices.Pasteboard -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| MAX_RECORD_NUM7+ | number | Yes | No | Maximum number of records allowed in a **PasteData** object. | -| MIMETYPE_TEXT_HTML7+ | string | Yes | No | MIME type of the HTML text. | -| MIMETYPE_TEXT_WANT7+ | string | Yes | No | MIME type of the Want text. | -| MIMETYPE_TEXT_PLAIN7+ | string | Yes | No | MIME type of the plain text. | -| MIMETYPE_TEXT_URI7+ | string | Yes | No | MIME type of the URI text. | +| MAX_RECORD_NUM7+ | number | Yes| No| Maximum number of records in a **PasteData** object.| +| MIMETYPE_TEXT_HTML7+ | string | Yes| No| MIME type of the HTML content.| +| MIMETYPE_TEXT_WANT7+ | string | Yes| No| MIME type of the Want content.| +| MIMETYPE_TEXT_PLAIN7+ | string | Yes| No| MIME type of the plain text content.| +| MIMETYPE_TEXT_URI7+ | string | Yes| No| MIME type of the URI content.| +| MIMETYPE_PIXELMAP9+ | string | Yes| No| MIME type of the pixel map.| ## pasteboard.createPlainTextData -createPlainTextData(text:string): PasteData +createPlainTextData(text: string): PasteData -Creates a **PasteData** object for plain text. +Creates a **PasteData** object of the plain text type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| text | string | Yes | Plain text. | +| text | string | Yes| Plain text.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object with the specified content. | +| [PasteData](#pastedata) | **PasteData** object.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("content"); - ``` +```js +var pasteData = pasteboard.createPlainTextData("content"); +``` ## pasteboard.createHtmlData7+ -createHtmlData(htmlText:string): PasteData +createHtmlData(htmlText: string): PasteData -Creates a **PasteData** object for HTML text. +Creates a **PasteData** object of the HTML type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| htmlText | string | Yes | HTML text. | +| htmlText | string | Yes| HTML content.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object with the specified content. | +| [PasteData](#pastedata) | **PasteData** object.| **Example** - ```js - var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; - var pasteData = pasteboard.createHtmlData(html); - ``` +```js +var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; +var pasteData = pasteboard.createHtmlData(html); +``` ## pasteboard.createWantData7+ -createWantData(want:Want): PasteData +createWantData(want: Want): PasteData -Creates a **PasteData** object for Want text. +Creates a **PasteData** object of the Want type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want text. | +| want | [Want](js-apis-application-Want.md) | Yes| Want content.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object with the specified content. | +| [PasteData](#pastedata) | **PasteData** object.| **Example** - ```js - var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" - }; - var pasteData = pasteboard.createWantData(object); - ``` +```js +var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" +}; +var pasteData = pasteboard.createWantData(object); +``` ## pasteboard.createUriData7+ -createUriData(uri:string): PasteData +createUriData(uri: string): PasteData -Creates a **PasteData** object for URI text. +Creates a **PasteData** object of the URI type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI text. | +| uri | string | Yes| URI content.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object with the specified content. | +| [PasteData](#pastedata) | **PasteData** object.| + +**Example** + +```js +var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); +``` + + +## pasteboard.createPixelMapData9+ + +createPixelMapData(pixelMap: image.PixelMap): PasteData + +Creates a **PasteData** object of the pixel map type. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pixelMap | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Pixel map.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [PasteData](#pastedata) | **PasteData** object.| + +**Example** + +```js +import image from '@ohos.multimedia.image'; + +var buffer = new ArrayBuffer(128) +var opt = { + size: { height: 3, width: 5 }, + pixelFormat: 3, + editable: true, + alphaType: 1, + scaleMode: 1 +} +image.createPixelMap(buffer, opt).then((pixelMap) => { + var pasteData = pasteboard.createPixelMapData(pixelMap); +}) +``` + +## pasteboard.createData9+ + +createData(mimeType: string, value: ArrayBuffer): PasteData; + +Creates a **PasteData** object of a custom type. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| mimeType | string | Yes| MIME type of custom data.| +| value | ArrayBuffer | Yes| Content of custom data.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [PasteData](#pastedata) | **PasteData** object.| **Example** ```js - var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); + var dataXml = new ArrayBuffer(256) + var pasteData = pasteboard.createData('app/xml', dataXml) ``` ## pasteboard.createPlainTextRecord7+ -createPlainTextRecord(text:string): PasteDataRecord +createPlainTextRecord(text: string): PasteDataRecord Creates a **PasteDataRecord** object of the plain text type. @@ -151,26 +216,26 @@ Creates a **PasteDataRecord** object of the plain text type. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| text | string | Yes | Plain text. | +| text | string | Yes| Plain text.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New plain text record. | +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the plain text type.| **Example** - ```js - var record = pasteboard.createPlainTextRecord("hello"); - ``` +```js +var record = pasteboard.createPlainTextRecord("hello"); +``` ## pasteboard.createHtmlTextRecord7+ -createHtmlTextRecord(htmlText:string): PasteDataRecord +createHtmlTextRecord(htmlText: string): PasteDataRecord Creates a **PasteDataRecord** object of the HTML text type. @@ -178,172 +243,277 @@ Creates a **PasteDataRecord** object of the HTML text type. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| htmlText | string | Yes | HTML text. | +| htmlText | string | Yes| HTML content.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New HTML record. | +| [PasteDataRecord](#pastedatarecord7) | **PasteDataRecord** object of the HTML text type.| **Example** - ```js - var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; - var record = pasteboard.createHtmlTextRecord(html); - ``` +```js +var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; +var record = pasteboard.createHtmlTextRecord(html); +``` ## pasteboard.createWantRecord7+ -createWantRecord(want:Want): PasteDataRecord +createWantRecord(want: Want): PasteDataRecord -Creates a **PasteDataRecord** object of the Want text type. +Creates a **PasteDataRecord** object of the Want type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want text. | +| want | [Want](js-apis-application-Want.md) | Yes| Want content.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New Want record. | +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the Want type.| **Example** - ```js - var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" - }; - var record = pasteboard.createWantRecord(object); - ``` +```js +var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" +}; +var record = pasteboard.createWantRecord(object); +``` ## pasteboard.createUriRecord7+ -createUriRecord(uri:string): PasteDataRecord +createUriRecord(uri: string): PasteDataRecord + +Creates a **PasteDataRecord** object of the URI type. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uri | string | Yes| URI content.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the URI type.| + +**Example** + +```js +var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); +``` + -Creates a **PasteDataRecord** object of the URI text type. +## pasteboard.createPixelMapRecord9+ + +createPixelMapRecord(pixelMap: image.PixelMap): PasteDataRecord + +Creates a **PasteDataRecord** object of the pixel map type. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pixelMap | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Pixel map.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the pixel map type.| + +**Example** + +```js +import image from '@ohos.multimedia.image'; + +var buffer = new ArrayBuffer(128) +var opt = { + size: { height: 3, width: 5 }, + pixelFormat: 3, + editable: true, + alphaType: 1, + scaleMode: 1 +} +image.createPixelMap(buffer, opt).then((pixelMap) => { + var record = pasteboard.createPixelMapRecord(pixelMap); +}) +``` + +## pasteboard.createRecord9+ + +createRecord(mimeType: string, value: ArrayBuffer):PasteDataRecord; + +Creates a **PasteDataRecord** object of the custom type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI text. | +| mimeType | string | Yes| MIME type of custom data.| +| value | ArrayBuffer | Yes| Content of custom data.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New URI record. | +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the custom type.| **Example** ```js - var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); + var dataXml = new ArrayBuffer(256) + var pasteDataRecord = pasteboard.createRecord('app/xml', dataXml); ``` +## pasteboard.getSystemPasteboard + +getSystemPasteboard(): SystemPasteboard + +Obtains this **SystemPasteboard** object. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Return value** + +| Type| Description| +| -------- | -------- | +| [SystemPasteboard](#systempasteboard) | **SystemPasteboard** object.| + +**Example** + +```js +var systemPasteboard = pasteboard.getSystemPasteboard(); +``` + +## ShareOption9+ + +Enumerates the paste options of data. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +| Name | Description | +| ----- | ----------------------- | +| InApp |Only intra-application pasting is allowed. | +| LocalDevice |Paste is allowed in any application on the local device. | +| CrossDevice |Paste is allowed in any application across devices. | + + ## PasteDataProperty7+ Defines the properties of all data records on the pasteboard, including the timestamp, data type, and additional data. **System capability**: SystemCapability.MiscServices.Pasteboard -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| additions | {[key: string]: object} | Yes | Yes | Additional property data. | -| mimeTypes | Array<string> | Yes | No | Non-repeating data types of the data records on the pasteboard. | -| tag | string | Yes | Yes | User-defined tag. | -| timestamp | number | Yes | No | Timestamp at which the data is written to the pasteboard, in milliseconds. | -| localOnly | boolean | Yes | Yes | Whether local access only is set for the pasteboard.
- The default value is **true**.
- **true**: The **PasteData** is set for local access only.
- **false**: The **PasteData** can be shared between devices. | +| additions7+ | {[key:string]:object} | Yes| Yes| Additional data.| +| mimeTypes7+ | Array<string> | Yes| No| Non-repeating data types of the data records on the pasteboard.| +| tag7+ | string | Yes| Yes| Custom tag.| +| timestamp7+ | number | Yes| No| Timestamp when data is written to the pasteboard (unit: ms).| +| localOnly7+ | boolean | Yes| Yes| Whether the pasteboard content is set for local access only. The default value is **true**.
- **true**: The pasteboard content is set for local access only.
- **false**: The pasteboard content can be shared between devices.| +| shareOption9+ | [ShareOption](#shareoption9) | Yes| Yes| Where the pasteboard content can be pasted. If this attribute is set incorrectly or not set, the default value **CrossDevice** is used.| ## PasteDataRecord7+ -A data record is an abstract definition of the content on the pasteboard. The pasteboard content consists of one or more plain text, HTML, URI, or Want records. +Provides **PasteDataRecord** APIs. A **PasteDataRecord** is an abstract definition of the content on the pasteboard. The pasteboard content consists of one or more plain text, HTML, URI, or Want records. ### Attributes **System capability**: SystemCapability.MiscServices.Pasteboard -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| htmlText7+ | string | Yes | No | HTML text. | -| want7+ | [Want](js-apis-application-Want.md) | Yes | No | Want text. | -| mimeType7+ | string | Yes | No | Data type. | -| plainText7+ | string | Yes | No | Plain text. | -| uri7+ | string | Yes | No | URI text. | +| htmlText7+ | string | Yes| No| HTML content.| +| want7+ | [Want](js-apis-application-Want.md) | Yes| No| Want content.| +| mimeType7+ | string | Yes| No| Data type.| +| plainText7+ | string | Yes| No| Plain text.| +| uri7+ | string | Yes| No| URI content.| +| pixelMap9+ | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| No| Pixel map.| +| data9+ | {[mimeType: string]: ArrayBuffer} | Yes| No| Content of custom data.| ### convertToText7+ convertToText(): Promise<string> -Forcibly converts the content in this **PasteData** object to the plain text. This API uses a promise to return the result. +Forcibly converts the content in a **PasteData** object to text. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the plain text content after conversion is returned. Otherwise, error information is returned. | +| Promise<string> | Promise used to return the text obtained from the conversion.| **Example** - ```js - var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); - record.convertToText().then((data) => { - console.info('convertToText success data : ' + JSON.stringify(data)); - }).catch((error) => { - console.error('convertToText failed because ' + JSON.stringify(error)); - }); - ``` +```js +var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); +record.convertToText().then((data) => { + console.info('Succeeded in converting to text. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to convert to text. Cause: ' + JSON.stringify(err)); +}); +``` ### convertToText7+ convertToText(callback: AsyncCallback<string>): void -Forcibly converts the content in this **PasteData** object to the plain text. This API uses an asynchronous callback to return the result. +Forcibly converts the content in a **PasteData** object to text. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. If this callback is successful, the plain text content after conversion is returned. Otherwise, error information is returned. | +| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the text obtained from the conversion. Otherwise, **err** is error information.| **Example** - ```js - var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); - record.convertToText((err, data) => { - if (err) { - console.error('convertToText failed because ' + JSON.stringify(err)); - return; - } - console.info('convertToText success data : ' + JSON.stringify(data)); - }); - ``` +```js +var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); +record.convertToText((err, data) => { + if (err) { + console.error('Failed to convert to text. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in converting to text. Data: ' + JSON.stringify(data)); +}); +``` ## PasteData -Before calling any **PasteData** method, you must obtain a **PasteData** object. +Provides **PasteData** APIs. + +Before calling any **PasteData** API, you must obtain a **PasteData** object. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -356,93 +526,126 @@ getPrimaryText(): string Obtains the plain text of the primary record. - **System capability**: SystemCapability.MiscServices.Pasteboard -**Return value** +**Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| string | Plain text. | +| string | Plain text.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var plainText = pasteData.getPrimaryText(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var plainText = pasteData.getPrimaryText(); +``` ### getPrimaryHtml7+ getPrimaryHtml(): string -Obtains the HTML text of the primary record. +Obtains the HTML content of the primary record. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| string | HTML text. | +| string | HTML content.| **Example** - ```js - var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; - var pasteData = pasteboard.createHtmlData(html); - var htmlText = pasteData.getPrimaryHtml(); - ``` +```js +var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; +var pasteData = pasteboard.createHtmlData(html); +var htmlText = pasteData.getPrimaryHtml(); +``` ### getPrimaryWant7+ getPrimaryWant(): Want -Obtains the **Want** object of the primary record. +Obtains the Want object of the primary record. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [Want](js-apis-application-Want.md) | Want object. | +| [Want](js-apis-application-Want.md) | Want object.| **Example** - ```js - var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" - }; - var pasteData = pasteboard.createWantData(object); - var want = pasteData.getPrimaryWant(); - ``` +```js +var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" +}; +var pasteData = pasteboard.createWantData(object); +var want = pasteData.getPrimaryWant(); +``` ### getPrimaryUri7+ getPrimaryUri(): string -Obtains the URI text of the primary record. +Obtains the URI of the primary record. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| string | URI text. | +| string | URI content.| **Example** - ```js - var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); - var uri = pasteData.getPrimaryUri(); - ``` +```js +var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); +var uri = pasteData.getPrimaryUri(); +``` + + +### getPrimaryPixelMap9+ + +getPrimaryPixelMap(): image.PixelMap + +Obtains the pixel map of the primary record. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Return value** + +| Type| Description| +| -------- | -------- | +| [image.PixelMap](js-apis-image.md#pixelmap7) | Pixel map.| + +**Example** + +```js +import image from '@ohos.multimedia.image'; + +var buffer = new ArrayBuffer(128) +var opt = { + size: { height: 3, width: 5 }, + pixelFormat: 3, + editable: true, + alphaType: 1, + scaleMode: 1 +} +image.createPixelMap(buffer, opt).then((pixelMap) => { + var pasteData = pasteboard.createPixelMapData(pixelMap); + var pixelMap = pasteData.getPrimaryPixelMap(); +}) +``` ### addTextRecord7+ @@ -451,98 +654,158 @@ addTextRecord(text: string): void Adds a plain text record to this pasteboard, and adds **MIME_TEXT_PLAIN** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 128 data records. +The pasteboard supports a maximum number of 512 data records. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| text | string | Yes | Plain text. | +| text | string | Yes| Plain text.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - pasteData.addTextRecord("good"); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +pasteData.addTextRecord("good"); +``` ### addHtmlRecord7+ addHtmlRecord(htmlText: string): void -Adds an HTML text record to this pasteboard, and adds **MIMETYPE_TEXT_HTML** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. +Adds an HTML record to this pasteboard, and adds **MIMETYPE_TEXT_HTML** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 128 data records. +The pasteboard supports a maximum number of 512 data records. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| htmlText | string | Yes | HTML text. | +| htmlText | string | Yes| HTML content.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; - pasteData.addHtmlRecord(html); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; +pasteData.addHtmlRecord(html); +``` ### addWantRecord7+ addWantRecord(want: Want): void -Adds a Want text record to this pasteboard, and adds **MIMETYPE_TEXT_WANT** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. +Adds a Want record to this pasteboard, and adds **MIMETYPE_TEXT_WANT** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 128 data records. +The pasteboard supports a maximum number of 512 data records. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want object. | +| want | [Want](js-apis-application-Want.md) | Yes| Want object.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" - }; - pasteData.addWantRecord(object); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" +}; +pasteData.addWantRecord(object); +``` ### addUriRecord7+ addUriRecord(uri: string): void -Adds a URI text record to this pasteboard, and adds **MIMETYPE_TEXT_URI** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. +Adds a URI record to this pasteboard, and adds **MIMETYPE_TEXT_URI** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 128 data records. +The pasteboard supports a maximum number of 512 data records. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI text. | +| uri | string | Yes| URI content.| + +**Example** + +```js +var pasteData = pasteboard.createPlainTextData("hello"); +pasteData.addUriRecord("dataability:///com.example.myapplication1/user.txt"); +``` + +### addPixelMapRecord9+ + +addPixelMapRecord(pixelMap: image.PixelMap): void + +Adds a pixel map record to this pasteboard, and adds **MIMETYPE_PIXELMAP** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. + +The pasteboard supports a maximum number of 512 data records. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pixelMap | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Pixel map.| + +**Example** + +```js +import image from '@ohos.multimedia.image'; + +var buffer = new ArrayBuffer(128) +var opt = { + size: { height: 3, width: 5 }, + pixelFormat: 3, + editable: true, + alphaType: 1, + scaleMode: 1 +} +image.createPixelMap(buffer, opt).then((pixelMap) => { + var record = pasteboard.createPlainTextData("hello").addPixelMapRecord(pixelMap); +}) +``` + + +### addRecord9+ + +addRecord(mimeType: string, value: ArrayBuffer): void + +Adds a custom-type record to this pasteboard, and adds the custom type to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. + +The pasteboard supports a maximum number of 512 data records. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| mimeType | string | Yes| MIME type of custom data.| +| value | ArrayBuffer | Yes| Content of custom data.| **Example** ```js - var pasteData = pasteboard.createPlainTextData("hello"); - pasteData.addUriRecord("dataability:///com.example.myapplication1?user.txt"); + var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); + var dataXml = new ArrayBuffer(256) + pasteData.addRecord('app/xml', dataXml); ``` @@ -552,423 +815,427 @@ addRecord(record: PasteDataRecord): void Adds a data record to this pasteboard, and adds its type to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -The pasteboard supports a maximum number of 128 data records. +The pasteboard supports a maximum number of 512 data records. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| record | [PasteDataRecord](#pastedatarecord7) | Yes | Record to add. | +| record | [PasteDataRecord](#pastedatarecord7) | Yes| Record to add.| **Example** - ```js - var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1?user.txt"); - var textRecord = pasteboard.createPlainTextRecord("hello"); - var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; - var htmlRecord = pasteboard.createHtmlTextRecord(html); - pasteData.addRecord(textRecord); - pasteData.addRecord(htmlRecord); - ``` +```js +var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); +var textRecord = pasteboard.createPlainTextRecord("hello"); +var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; +var htmlRecord = pasteboard.createHtmlTextRecord(html); +pasteData.addRecord(textRecord); +pasteData.addRecord(htmlRecord); +``` ### getMimeTypes7+ getMimeTypes(): Array<string> -Obtains **mimeTypes** in [PasteDataProperty](#pastedataproperty7) from this pasteboard. If the pasteboard is empty, the returned list is also empty. +Obtains a list of **mimeTypes** objects in [PasteDataProperty](#pastedataproperty7) from this pasteboard. If the pasteboard is empty, the returned list is also empty. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Array<string> | List of non-duplicate MIME types. | +| Array<string> | Non-repeating data types of the data records on the pasteboard.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var types = pasteData.getMimeTypes(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var types = pasteData.getMimeTypes(); +``` ### getPrimaryMimeType7+ getPrimaryMimeType(): string -Obtains the data type of the primary record. +Obtains the data type of the primary record in this pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| string | Data type of the primary record. | +| string | Data type of the primary record.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var type = pasteData.getPrimaryMimeType(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var type = pasteData.getPrimaryMimeType(); +``` ### getProperty7+ getProperty(): PasteDataProperty -Obtains the property description object. +Obtains the property of the pasteboard data. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataProperty](#pastedataproperty7) | Property description object. | +| [PasteDataProperty](#pastedataproperty7) | Property of the pasteboard data.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var property = pasteData.getProperty(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var property = pasteData.getProperty(); +``` + + +### setProperty9+ + +setProperty(property: PasteDataProperty): void + +Sets the property (attributes) for the pasteboard data. Currently, only the **shareOption** attribute is supported. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| property | [PasteDataProperty](#pastedataproperty7) | Yes| Property of the pasteboard data.| + +**Example** + +```js +var pasteData = pasteboard.createHtmlData('application/xml'); +let prop = pasteData.getProperty(); +prop.shareOption = pasteboard.ShareOption.InApp; +pasteData.setProperty(prop); +``` ### getRecordAt7+ getRecordAt(index: number): PasteDataRecord -Obtains the record with the specified index. +Obtains the specified record in the pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes | Index of the specified record. | +| index | number | Yes| Index of the target record.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | Record with the specified index. | +| [PasteDataRecord](#pastedatarecord7) | Record with the specified index.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var record = pasteData.getRecordAt(0); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var record = pasteData.getRecordAt(0); +``` ### getRecordCount7+ getRecordCount(): number -Obtains the number of data records in this pasteboard. +Obtains the number of records in the pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| number | Number of records. | +| number | Number of records.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var count = pasteData.getRecordCount(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var count = pasteData.getRecordCount(); +``` ### getTag7+ getTag(): string -Obtains the user-defined tag content. If the tag content is not set, null is returned. +Obtains the custom tag from the pasteboard. If no custom tag is set, null is returned. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| string | User-defined tag content if obtained and null if no tag is set. | +| string | Custom tag. If no custom tag is set, null is returned.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var tag = pasteData.getTag(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var tag = pasteData.getTag(); +``` ### hasMimeType7+ hasMimeType(mimeType: string): boolean -Checks whether the content of this pasteboard contains the specified data type. +Checks whether the pasteboard contains data of the specified type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mimeType | string | Yes | Type of the data to query. | +| mimeType | string | Yes| Type of the data to query.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| boolean | Returns **true** if the specified data type exists; returns **false** otherwise. | +| boolean | Returns **true** if the specified data type exists; returns **false** otherwise.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); +``` ### removeRecordAt7+ removeRecordAt(index: number): boolean -Removes the data record with a specified index from this pasteboard. +Removes the record with the specified index from the pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes | Specified index. | +| index | number | Yes| Specified index.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var isRemove = pasteData.removeRecordAt(0); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var isRemove = pasteData.removeRecordAt(0); +``` ### replaceRecordAt7+ replaceRecordAt(index: number, record: PasteDataRecord): boolean -Replaces the data record with a specified index in this pasteboard. +Replaces the record with the specified index in the pasteboard with a new record. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes | Specified index. | -| record | [PasteDataRecord](#pastedatarecord7) | Yes | New record. | +| index | number | Yes| Specified index.| +| record | [PasteDataRecord](#pastedatarecord7) | Yes| New record.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); - var isReplace = pasteData.replaceRecordAt(0, record); - ``` - - -## pasteboard.getSystemPasteboard - -getSystemPasteboard(): SystemPasteboard - -Obtains the system pasteboard. - -**System capability**: SystemCapability.MiscServices.Pasteboard - -**Return value** - -| Type | Description | -| -------- | -------- | -| [SystemPasteboard](#systempasteboard) | System pasteboard. | - -**Example** - - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - ``` - +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); +var isReplace = pasteData.replaceRecordAt(0, record); +``` ## SystemPasteboard -Before calling any **SystemPasteboard** method, you must obtain a **SystemPasteboard** object using [getSystemPasteboard](#pasteboardgetsystempasteboard). +Provides **SystemPasteboard** APIs. -``` +Before calling any **SystemPasteboard** API, you must obtain a **SystemPasteboard** object using [getSystemPasteboard](#pasteboardgetsystempasteboard). + +```js var systemPasteboard = pasteboard.getSystemPasteboard(); ``` ### setPasteData -setPasteData(data:PasteData, callback:AsyncCallback<void>): void +setPasteData(data: PasteData, callback: AsyncCallback<void>): void -Writes data to a pasteboard. This API uses an asynchronous callback to return the result. +Writes a **PasteData** object to the pasteboard. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| data | [PasteData](#pastedata) | Yes | **PasteData** object. | -| callback | AsyncCallback<void> | Yes | Callback used to return the data write result. | +| data | [PasteData](#pastedata) | Yes| **PasteData** object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("content"); - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.setPasteData(pasteData, (error, data) => { - if (error) { - console.error('Failed to setPasteData. Cause: ' + error.message); - return; - } - console.info('setPasteData successfully.'); - }); - ``` +```js +var pasteData = pasteboard.createPlainTextData("content"); +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setPasteData(pasteData, (err, data) => { + if (err) { + console.error('Failed to set PasteData. Cause: ' + err.message); + return; + } + console.info('Succeeded in setting PasteData.'); +}); +``` ### setPasteData -setPasteData(data:PasteData): Promise<void> +setPasteData(data: PasteData): Promise<void> -Writes data to a pasteboard. This API uses a promise to return the result. +Writes a **PasteData** object to the pasteboard. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| data | [PasteData](#pastedata) | **PasteData** object. | +| data | [PasteData](#pastedata) | **PasteData** object.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the data write result. | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("content"); - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.setPasteData(pasteData).then((data) => { - console.info('setPasteData success.'); - }).catch((error) => { - console.error('Failed to setPasteData. Cause: ' + error.message); - }); - ``` +```js +var pasteData = pasteboard.createPlainTextData("content"); +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setPasteData(pasteData).then((data) => { + console.info('Succeeded in setting PasteData.'); +}).catch((err) => { + console.error('Failed to set PasteData. Cause: ' + err.message); +}); +``` ### getPasteData -getPasteData( callback:AsyncCallback<PasteData>): void +getPasteData( callback: AsyncCallback<PasteData>): void -Reads the system pasteboard content. This API uses an asynchronous callback to return the result. +Obtains a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[PasteData](#pastedata)> | Yes | Callback used to return the system pasteboard data. | +| callback | AsyncCallback<[PasteData](#pastedata)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the system pasteboard data. Otherwise, **err** is an error object.| **Example** - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.getPasteData((error, pasteData) => { - if (error) { - console.error('Failed to getPasteData. Cause: ' + error.message); - return; - } - var text = pasteData.getPrimaryText(); - }); - ``` +```js +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getPasteData((err, pasteData) => { + if (err) { + console.error('Failed to get PasteData. Cause: ' + err.message); + return; + } + var text = pasteData.getPrimaryText(); +}); +``` ### getPasteData getPasteData(): Promise<PasteData> -Reads the system pasteboard content. This API uses a promise to return the result. +Obtains a **PasteData** object from the pasteboard. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[PasteData](#pastedata)> | Promise used to return the system pasteboard data. | +| Promise<[PasteData](#pastedata)> | Promise used to return the system pasteboard data.| **Example** - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.getPasteData().then((pasteData) => { - var text = pasteData.getPrimaryText(); - }).catch((error) => { - console.error('Failed to getPasteData. Cause: ' + error.message); - }) - ``` +```js +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getPasteData().then((pasteData) => { + var text = pasteData.getPrimaryText(); +}).catch((err) => { + console.error('Failed to get PasteData. Cause: ' + err.message); +}) +``` ### on('update')7+ on(type: 'update', callback: () =>void ): void -Subscribes to the content change event of the system pasteboard. If the pasteboard content changes, the callback is triggered. +Subscribes to the content change event of the system pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Data type. The value **update** indicates the pasteboard content has changed. | -| callback | function | Yes | Callback invoked when the pasteboard content changes. | +| type | string | Yes| Event type. The value **'update'** indicates changes in the pasteboard content.| +| callback | function | Yes| Callback invoked when the pasteboard content changes.| **Example** - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - var listener = () => { - console.info('The system pasteboard has changed'); - }; - systemPasteboard.on('update', listener); - ``` +```js +var systemPasteboard = pasteboard.getSystemPasteboard(); +var listener = () => { + console.info('The system pasteboard has changed.'); +}; +systemPasteboard.on('update', listener); +``` ### off('update')7+ @@ -981,120 +1248,120 @@ Unsubscribes from the system pasteboard content change event. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Data type. The value **update** indicates the pasteboard content has changed. | -| callback | function | No | Callback invoked when the pasteboard content changes. | +| type | string | Yes| Event type. The value **'update'** indicates changes in the pasteboard content.| +| callback | function | No| Callback invoked when the pasteboard content changes.| **Example** - ```js - let listener = () => { - console.info('The system pasteboard has changed'); - }; - systemPasteboard.off('update', listener); - ``` +```js +let listener = () => { + console.info('The system pasteboard has changed.'); +}; +systemPasteboard.off('update', listener); +``` ### hasPasteData7+ hasPasteData(callback: AsyncCallback<boolean>): void -Checks whether the system pasteboard contains content. This API uses an asynchronous callback to return the result. +Checks whether the system pasteboard contains data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Returns **true** if the pasteboard contains content; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if the system pasteboard contains data; returns **false** otherwise.| **Example** - ```js - systemPasteboard.hasPasteData((err, data) => { - if (err) { - console.error('failed to hasPasteData because ' + JSON.stringify(err)); - return; - } - console.info('success hasPasteData : ' + JSON.stringify(data)); - }); - ``` +```js +systemPasteboard.hasPasteData((err, data) => { + if (err) { + console.error('Failed to check the PasteData. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking the PasteData. Data: ' + JSON.stringify(data)); +}); +``` ### hasPasteData7+ -hasPasteData(): Promise<boolean> +hasPasteData(): Promise<boolean> -Checks whether the system pasteboard contains content. This API uses a promise to return the result. +Checks whether the system pasteboard contains data. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Returns **true** if the pasteboard contains content; returns **false** otherwise. | +| Promise<boolean> | Promise used to return the result. Returns **true** if the system pasteboard contains data; returns **false** otherwise.| **Example** - ```js - systemPasteboard.hasPasteData().then((data) => { - console.info('success hasPasteData : ' + JSON.stringify(data)); - }).catch((error) => { - console.error('failed to hasPasteData because ' + JSON.stringify(error)); - }); - ``` +```js +systemPasteboard.hasPasteData().then((data) => { + console.info('Succeeded in checking the PasteData. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to check the PasteData. Cause: ' + JSON.stringify(err)); +}); +``` ### clear7+ -clear(callback: AsyncCallback<void>): void +clear(callback: AsyncCallback<void>): void -Clears the system pasteboard content. This API uses an asynchronous callback to return the result. +Clears the system pasteboard. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Example** - ```js - systemPasteboard.clear((err, data) => { - if (err) { - console.error('failed to clear because ' + JSON.stringify(err)); - return; - } - console.info('success clear'); - }); - ``` +```js +systemPasteboard.clear((err, data) => { + if (err) { + console.error('Failed to clear the PasteData. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in clearing the PasteData.'); +}); +``` ### clear7+ -clear(): Promise<void> +clear(): Promise<void> -Clears the system pasteboard content. This API uses a promise to return the result. +Clears the system pasteboard. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. | +| Promise<void> | Promise that returns no value.| **Example** - ```js - systemPasteboard.clear().then((data) => { - console.info('success clear'); - }).catch((error) => { - console.error('failed to clear because ' + JSON.stringify(error)); - }); - ``` +```js +systemPasteboard.clear().then((data) => { + console.info('Succeeded in clearing the PasteData.'); +}).catch((err) => { + console.error('Failed to clear the PasteData. Cause: ' + JSON.stringify(err)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index d133b1b37776187ac1120f42ead17e98273f0db4..b397ba221d3d570e3b5eca2f551ecee228bdfc35 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -37,4 +37,4 @@ export default class MainAbility extends Ability { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index 76d8bef4a2a4dd2606207a1f71c91d6703c99d43..1f3f64ff1aaaa2b5267cdfc55632c46b986df74f 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -3,7 +3,6 @@ The **PrivacyManager** module provides APIs for privacy management, such as management of permission usage records. > **NOTE** -> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module are system APIs and cannot be called by third-party applications. @@ -16,7 +15,7 @@ import privacyManager from '@ohos.privacyManager'; ## privacyManager.addPermissionUsedRecord -addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise<number> +addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise<void> Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result. The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. @@ -29,7 +28,7 @@ The permission usage record includes the application identity of the invoker, na | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID of the invoker. | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission.| | successCount | number | Yes | Number of successful accesses.| | failCount | number | Yes | Number of failed accesses.| @@ -38,20 +37,28 @@ The permission usage record includes the application identity of the invoker, na | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| +| Promise<void> | Promise that returns no value.| **Example** ```js -var tokenID = appInfo.accessTokenId; // accessTokenId can be obtained by using getApplicationInfo(). -privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0).then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0).then(() => { + console.log('addPermissionUsedRecord success'); + }).catch((err) => { + console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## privacyManager.addPermissionUsedRecord -addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback<number>): void +addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback<void>): void Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result. The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. @@ -64,19 +71,29 @@ The permission usage record includes the application identity of the invoker, na | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID of the invoker. | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission.| | successCount | number | Yes | Number of successful accesses.| | failCount | number | Yes | Number of failed accesses.| -| callback | AsyncCallback<number> | Yes | Callback used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** ```js -var tokenID = appInfo.accessTokenId; // accessTokenId can be obtained by using getApplicationInfo(). -privacyManager.privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (err, data) => { - console.log(`callback: data->${JSON.stringify(data)}`); -}); +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (data, err) => { + if (err) { + console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); + } else { + console.log('addPermissionUsedRecord success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## privacyManager.getPermissionUsedRecords @@ -104,19 +121,27 @@ Obtains historical permission usage records. This API uses a promise to return t **Example** ```js +import privacyManager from '@ohos.privacyManager'; + let request = { "tokenId": 1, - "isRemote": 1, + "isRemote": false, "deviceId": "device", "bundleName": "bundle", - "permissionNames": 1, + "permissionNames": [], "beginTime": 0, "endTime": 1, "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; -privacyManager.getPermissionUsedRecords(request).then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + privacyManager.getPermissionUsedRecords(request).then((data) => { + console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + }).catch((err) => { + console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## privacyManager.getPermissionUsedRecords @@ -134,24 +159,256 @@ Obtains historical permission usage records. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | | request | [PermissionUsedRequest](#permissionusedrequest) | Yes| Request for querying permission usage records.| -| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback used to return the permission usage records obtained.| +| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback invoked to return the permission usage records obtained.| **Example** ```js +import privacyManager from '@ohos.privacyManager'; + let request = { "tokenId": 1, - "isRemote": 1, + "isRemote": false, "deviceId": "device", "bundleName": "bundle", - "permissionNames": 1, + "permissionNames": [], "beginTime": 0, "endTime": 1, "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; -privacyManager.getPermissionUsedRecords(request, (err, data) => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + privacyManager.getPermissionUsedRecords(request, (err, data) => { + if (err) { + console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + } else { + console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.startUsingPermission + +startUsingPermission(tokenID: number, permissionName: string): Promise<void> + +Starts to record a permission usage event. This API is called by a system service and uses a promise to return the result. The permissions used by an app in the foreground and background can be observed, and the permission usage records can be saved. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS").then(() => { + console.log('startUsingPermission success'); + }).catch((err) => { + console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.startUsingPermission + +startUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void + +Starts to record a permission usage event. This API is called by a system service and uses an asynchronous callback to return the result. The permissions used by an app in the foreground and background can be observed and saved. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | --------------------- | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (data, err) => { + if (err) { + console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('startUsingPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.stopUsingPermission + +stopUsingPermission(tokenID: number, permissionName: string): Promise<void> + +Stops recording the permission usage event. This API is called by a system service and uses a promise to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS").then(() => { + console.log('stopUsingPermission success'); + }).catch((err) => { + console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.stopUsingPermission + +stopUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void + +Stops recording the permission usage event. This API is called by the system service and uses an asynchronous callback to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | --------------------- | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (data, err) => { + if (err) { + console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('stopUsingPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.on + +on(type: 'activeStateChange', permissionNameList: Array<string>, callback: Callback<ActiveChangeResponse>): void + +Subscribes to the changes in the usage of the specified permission list. This API uses a callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type to subscribe to. The value is **activeStateChange**, which indicates permission usage change event. | +| permissionNameList | Array<string> | No | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | +| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback invoked to return a change in permission usage.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let permissionNameList: Array = []; +try { + atManager.on('activeStateChange', permissionNameList, (data) => { + console.debug("receive permission state change, data:" + JSON.stringify(data)); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.off + +off(type: 'activeStateChange', permissionNameList: Array<string>, callback?: Callback<ActiveChangeResponse>): void; + +Unsubscribes from the changes in the usage of the specified permission list. This API uses a callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type to subscribe to. The value is **activeStateChange**, which indicates permission usage change event. | +| permissionNameList | Array<string> | No | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| +| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback for the permission usage change event.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let permissionNameList: Array = []; +try { + privacyManager.off('activeStateChange', permissionNameList); +}catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## PermissionUsageFlag @@ -236,3 +493,28 @@ Represents the details of a single access record. | status | number | No | Access status. | | timestamp | number | No | Access timestamp, in ms.| | accessDuration | number | No | Access duration, in ms. | + +## PermissionActiveStatus + +Enumerates of permission usage statuses. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Default Value| Description | +| ------------------------- | ------ | ---------------- | +| PERM_INACTIVE | 0 | The permission is not used. | +| PERM_ACTIVE_IN_FOREGROUND | 1 | The permission is being used in the foreground.| +| PERM_ACTIVE_IN_BACKGROUND | 2 | The permission is being used in the background.| + +## ActiveChangeResponse + +Defines the detailed permission usage information. + + **System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Readable| Writable| Description | +| -------------- | ---------------------- | ---- | ---- | --------------------- | +| tokenId | number | Yes | No | Token ID of the application that applies for the permission. | +| permissionName | string | Yes | No | Name of the permission.| +| deviceId | string | Yes | No | Device number. | +| activeStatus | [PermissionActiveStatus](#permissionactivestatus) | Yes | No | Permission usage status. | diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index d094a5c7e3abd27ebc042ab377543a3d2898b1e1..ec920f58cab6825ce1dd286f42d1eb24e759f10b 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -384,6 +384,27 @@ promise.then(data => { }); ``` +## radio.isNrSupported7+ + +isNrSupported\(\): boolean + +Checks whether the current device supports 5G \(NR\). + +**System capability**: SystemCapability.Telephony.CoreService + +**Return value** + +| Type | Description | +| ------- | -------------------------------- | +| boolean | - **true**: The current device supports 5G \(NR\).
- **false**: The current device does not support 5G \(NR\).| + +**Example** + +```js +let result = radio.isNrSupported(); +console.log("Result: "+ result); +``` + ## radio.isNrSupported8+ @@ -1100,12 +1121,12 @@ Sets the network selection mode. This API uses an asynchronous callback to retur let networkInformation={ operatorName: "China Mobile", operatorNumeric: "898600", - state: 1, + state: radio.NetworkInformationState.NETWORK_AVAILABLE, radioTech: "CS" } let networkSelectionModeOptions={ - slotid: 0, - selectMode: 1, + slotId: 0, + selectMode: radio.NetworkSelectionMode.NETWORK_SELECTION_AUTOMATIC, networkInformation: networkInformation, resumeSelection: true } @@ -1144,12 +1165,12 @@ Sets the network selection mode. This API uses a promise to return the result. let networkInformation={ operatorName: "China Mobile", operatorNumeric: "898600", - state: 1, + state: radio.NetworkInformationState.NETWORK_AVAILABLE, radioTech: "CS" } let networkSelectionModeOptions={ - slotid: 0, - selectMode: 1, + slotId: 0, + selectMode: radio.NetworkSelectionMode.NETWORK_SELECTION_AUTOMATIC, networkInformation: networkInformation, resumeSelection: true } @@ -1190,7 +1211,7 @@ radio.getNetworkSearchInformation(0, (err, data) => { ## radio.getNetworkSearchInformation -getNetworkSearchInformation\(slotId: number\): Promise +getNetworkSearchInformation\(slotId: number\): Promise Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result. @@ -1586,7 +1607,7 @@ radio.getPreferredNetwork(0, (err, data) => { ## radio.getPreferredNetwork8+ -getPreferredNetwork(slotId: number): Promise +getPreferredNetwork(slotId: number): Promise Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. @@ -1642,7 +1663,7 @@ Obtains the IMS registration status of the specified IMS service type for the SI **Example** ```js -radio.getImsRegInfo(0, 1, (err, data) => { +radio.getImsRegInfo(0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1675,7 +1696,7 @@ Obtains the IMS registration status of the specified IMS service type for the SI **Example** ```js -let promise = radio.getImsRegInfo(0, 1); +let promise = radio.getImsRegInfo(0, radio.ImsServiceType.TYPE_VIDEO); promise.then(data => { console.log(`getImsRegInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1707,7 +1728,7 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci **Example** ```js -radio.on('imsRegStateChange', 0, 1, (err, data) => { +radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1736,7 +1757,7 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec **Example** ```js -radio.off('imsRegStateChange', 0, 1, (err, data) => { +radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index d2dcd1fdd0b4dd88d4a6917d260f052aa9198eca..245865cc40144c8910a4c245a9485641c0452627 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -233,61 +233,46 @@ Locks the screen. This API uses a promise to return the result. }); ``` +## EventType -## screenlock.on9+ - -on(type: 'beginWakeUp' | 'endWakeUp' | 'beginScreenOn' | 'endScreenOn' | 'beginScreenOff' | 'endScreenOff' | 'unlockScreen' | 'beginExitAnimation', callback: Callback\): void - -Subscribes to screen lock status changes. +Defines the system event type. **System capability**: SystemCapability.MiscServices.ScreenLock -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.| -| callback | Callback\ | Yes| Callback used to return the result.| - -**Example** - - ```js - screenlock.on('beginWakeUp', () => { - console.log('beginWakeUp triggered'); - }); - ``` - -## screenlock.on9+ - -on(type: 'beginSleep' | 'endSleep' | 'changeUser', callback: Callback\): void - -Subscribes to screen lock status changes. +| Name| Description| +| -------- | -------- | +| beginWakeUp | Wakeup starts when the event starts.| +| endWakeUp | Wakeup ends when the event ends.| +| beginScreenOn | Screen turn-on starts when the event starts.| +| endScreenOn | Screen turn-on ends when the event ends.| +| beginScreenOff | Screen turn-off starts when the event starts.| +| endScreenOff | Screen turn-off ends when the event ends.| +| unlockScreen | The screen is unlocked.| +| lockScreen | The screen is locked.| +| beginExitAnimation | Animation starts to exit.| +| beginSleep | The screen enters sleep mode.| +| endSleep | The screen exits sleep mode.| +| changeUser | The user is switched.| +| screenlockEnabled | Screen lock is enabled.| +| serviceRestart | The screen lock service is restarted.| + + +## SystemEvent + +Defines the structure of the system event callback. **System capability**: SystemCapability.MiscServices.ScreenLock -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.| -| callback | Callback\ | Yes| Callback used to return the result. | - -**Example** +| Name| Description| +| -------- | -------- | +| eventType | System event type.| +| params | System event parameters.| - ```js - screenlock.on('beginSleep', (why) => { - console.log('beginSleep triggered:' + why); - }); - ``` -## screenlock.on9+ +## screenlock.onSystemEvent9+ -on(type: 'screenlockEnabled', callback: Callback\): void +onSystemEvent(callback: Callback\): boolean -Subscribes to screen lock status changes. +Registers a callback for system events related to screen locking. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -297,41 +282,26 @@ Subscribes to screen lock status changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"screenlockEnabled"**: Screen lock is enabled.| -| callback | Callback\ | Yes| Callback used to return the result. | - -**Example** - - ```js - screenlock.on('screenlockEnabled', (isEnabled) => { - console.log('screenlockEnabled triggered, result:' + isEnabled); - }); - ``` - -## screenlock.off9+ +| callback | Callback\ | Yes| Callback for system events related to screen locking| -off(type: 'beginWakeUp' | 'endWakeUp' | 'beginScreenOn' | 'endScreenOn' | 'beginScreenOff' | 'endScreenOff' - | 'unlockScreen' | 'beginExitAnimation' | 'screenlockEnabled' | 'beginSleep' | 'endSleep' | 'changeUser', callback: Callback\): void - -Unsubscribes from screen lock status changes. - -**System capability**: SystemCapability.MiscServices.ScreenLock - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** +**Return value** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.
- **"screenlockEnabled"**: Screen lock is enabled.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.| -| callback | Callback\ | Yes| Callback used to return the result.| +| Type | Description | +| ------- | -------------------------------------------- | +| boolean | The value **true** means that the callback is registered successfully, and **false** means the opposite.| **Example** ```js - screenlock.off('beginWakeUp', () => { - console.log("callback"); - }); + let isSuccess = screenlock.onSystemEvent((err, event)=>{ + console.log(`onSystemEvent:callback:${event.eventType}`) + if (err) { + console.log(`onSystemEvent callback error -> ${JSON.stringify(err)}`); + } + }); + if (!isSuccess) { + console.log(`onSystemEvent result is false`) + } ``` ## screenlock.sendScreenLockEvent9+ @@ -375,7 +345,7 @@ Sends an event to the screen lock service. This API uses a promise to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.| -| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.| +| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock fails.
- **2**: The unlock is canceled.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 5b9107af6a142f762171272278e3ea543bb93b81..dd9d9e38aeaf04f38f38b12db89bc48888b70d7f 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -22,720 +22,888 @@ A sensor is a device to detect events or changes in an environment and send mess import sensor from '@ohos.sensor'; ``` -## sensor.on +## sensor.on9+ -### ACCELEROMETER +### ACCELEROMETER9+ -on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void +on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void -Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the acceleration sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### LINEAR_ACCELERATIONdeprecated +```js +try { + sensor.on(sensor.SensorId.ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void +### ACCELEROMETER_UNCALIBRATED9+ -Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>,options?: Options): void -This API is deprecated since API version 9. You are advised to use **Sensor.on.LINEAR_ACCELEROMETER9+** instead. +Subscribes to data of the uncalibrated acceleration sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### LINEAR_ACCELEROMETER9+ +```js +try { + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,callback:Callback<LinearAccelerometerResponse>, options?: Options): void +### AMBIENT_LIGHT9+ -Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the ambient light sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### ACCELEROMETER_UNCALIBRATED +```js +try { + sensor.on(sensor.SensorId.AMBIENT_LIGHT,function(data){ + console.info('Illumination: ' + data.intensity); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void +### AMBIENT_TEMPERATURE9+ -Subscribes to data changes of the uncalibrated acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the ambient temperature sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` -### GRAVITY +```js +try { + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE,function(data){ + console.info('Temperature: ' + data.temperature); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### BAROMETER9+ -on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void +on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, options?: Options): void -Subscribes to data changes of the gravity sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the barometer sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ + +```js +try { + sensor.on(sensor.SensorId.BAROMETER,function(data){ + console.info('Atmospheric pressure: ' + data.pressure); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### GRAVITY9+ + +on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: Options): void + +Subscribes to data of the gravity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.on(sensor.SensorId.GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GYROSCOPE +### GYROSCOPE9+ -on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void +on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options?: Options): void -Subscribes to data changes of the gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the gyroscope sensor. -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + +```js +try { + sensor.on(sensor.SensorId.GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GYROSCOPE_UNCALIBRATED +### GYROSCOPE_UNCALIBRATED9+ -on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void +on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>, + options?: Options): void -Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the uncalibrated gyroscope sensor. -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE -**System capability**: SystemCapability.Sensors.Sensor +**System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ + +```js +try { + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### SIGNIFICANT_MOTION +### HALL9+ -on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void +on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Options): void -Subscribes to data changes of the significant motion sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the Hall effect sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 10000000} - ); - ``` -### PEDOMETER_DETECTION +```js +try { + sensor.on(sensor.SensorId.HALL,function(data){ + console.info('Status: ' + data.status); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void +### HEART_RATE9+ -Subscribes to data changes of the pedometer detection sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the heart rate sensor. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | Callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 10000000} - ); - ``` -### PEDOMETER +```js +try { + sensor.on(sensor.SensorId.HEART_RATE,function(data){ + console.info('Heart rate: ' + data.heartRate); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void +### HUMIDITY9+ -Subscribes to data changes of the pedometer sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the humidity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ - console.info('Steps: ' + data.steps); - }, - {interval: 10000000} - ); - ``` -### AMBIENT_TEMPERATURE +```js +try { + sensor.on(sensor.SensorId.HUMIDITY,function(data){ + console.info('Humidity: ' + data.humidity); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### LINEAR_ACCELEROMETER9+ -on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void +on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>, + options?: Options): void -Subscribes to data changes of the ambient temperature sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ - console.info('Temperature: ' + data.temperature); - }, - {interval: 10000000} - ); - ``` -### MAGNETIC_FIELD +```js +try { + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void +### MAGNETIC_FIELD9+ -Subscribes to data changes of the magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void + +Subscribes to data of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ + +```js +try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### MAGNETIC_FIELD_UNCALIBRATED +### MAGNETIC_FIELD_UNCALIBRATED9+ -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void +on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void -Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the uncalibrated magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ + +```js +try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### PROXIMITY +### ORIENTATION9+ -on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void +on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,options?: Options): void -Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the orientation sensor. **System capability**: SystemCapability.Sensors.Sensor +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ - console.info('Distance: ' + data.distance); - }, - {interval: 10000000} - ); - ``` - -### HUMIDITY -on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void +```js +try { + sensor.on(sensor.SensorId.ORIENTATION,function(data){ + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -Subscribes to data changes of the humidity sensor. If this API is called multiple times for the same application, the last call takes effect. +### PEDOMETER9+ -**System capability**: SystemCapability.Sensors.Sensor +on(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +Subscribes to data of the pedometer sensor. -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ - console.info('Humidity: ' + data.humidity); - }, - {interval: 10000000} - ); - ``` +**Required permissions**: ohos.permission.ACTIVITY_MOTION -### BAROMETER +**System capability**: SystemCapability.Sensors.Sensor -on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void +**Error code** -Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**System capability**: SystemCapability.Sensors.Sensor +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ - console.info('Atmospheric pressure: ' + data.pressure); - }, - {interval: 10000000} - ); - ``` -### HALL +```js +try { + sensor.on(sensor.SensorId.PEDOMETER,function(data){ + console.info('Steps: ' + data.steps); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void +### PEDOMETER_DETECTION9+ -Subscribes to data changes of the Hall effect sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, + options?: Options): void -**System capability**: SystemCapability.Sensors.Sensor +Subscribe to data of the pedometer detection sensor. -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +**Required permissions**: ohos.permission.ACTIVITY_MOTION -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ - console.info('Status: ' + data.status); - }, - {interval: 10000000} - ); - ``` +**System capability**: SystemCapability.Sensors.Sensor -### AMBIENT_LIGHT +**Parameters** -on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -Subscribes to data changes of the ambient light sensor. If this API is called multiple times for the same application, the last call takes effect. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ - console.info(' Illumination: ' + data.intensity); - }, - {interval: 10000000} - ); - ``` -### ORIENTATION +```js +try { + sensor.on(sensor.SensorId.PEDOMETER_DETECTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void +### PROXIMITY9+ -Subscribes to data changes of the orientation sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, options?: Options): void + +Subscribes to data of the proximity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - }, - {interval: 10000000} - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -### HEART_RATEdeprecated +**Error code** -on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the heart rate sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -This API is deprecated since API version 9. You are advised to use **sensor.on.HEART_BEAT_RATE9+** instead. +**Example** -**Required permissions**: ohos.permission.READ_HEALTH_DATA +```js +try { + sensor.on(sensor.SensorId.PROXIMITY,function(data){ + console.info('Distance: ' + data.distance); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### ROTATION_VECTOR9+ + +on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>, + options?: Options): void + +Subscribes to data of the rotation vector sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ - console.info("Heart rate: " + data.heartRate); -}, - {interval: 10000000} -); +try { + sensor.on(sensor.SensorId.ROTATION_VECTOR,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -### HEART_BEAT_RATE9+ - -on(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback: Callback<HeartRateResponse>, options?: Options): void +### SIGNIFICANT_MOTION9+ -Subscribes to only one data change of the heart rate sensor. +on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, + options?: Options): void -**Required permissions**: ohos.permission.READ_HEALTH_DATA +Subscribes to data of the significant motion sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE,function(data){ - console.info("Heart rate: " + data.heartRate); -}, - {interval: 10000000} -); +try { + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -### ROTATION_VECTOR +### WEAR_DETECTION9+ -on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void +on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>, + options?: Options): void -Subscribes to data changes of the rotation vector sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the wear detection sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | - -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }, - {interval: 10000000} - ); - ``` - -### WEAR_DETECTION -on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -Subscribes to data changes of the wear detection sensor. If this API is called multiple times for the same application, the last call takes effect. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ + +```js +try { + sensor.on(sensor.SensorId.WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -## sensor.once +## sensor.once9+ -### ACCELEROMETER +### ACCELEROMETER9+ -once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void +once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>): void -Subscribes to only one data change of the acceleration sensor. +Subscribes to data of the acceleration sensor once. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### LINEAR_ACCELERATIONdeprecated +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void - -Subscribes to only one data change of the linear acceleration sensor. - -This API is deprecated since API version 9. You are advised to use **sensor.once.LINEAR_ACCELEROMETER9+** instead. +**Error code** -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**System capability**: 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**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { + +```js +try { + sensor.once(sensor.SensorId.ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); } ); - ``` +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### LINEAR_ACCELEROMETER9+ +### ACCELEROMETER_UNCALIBRATED9+ -once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,callback:Callback<LinearAccelerometerResponse>): void +once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>): void -Subscribes to only one data change of the linear acceleration sensor. +Subscribes to data of the uncalibrated acceleration sensor once. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### ACCELEROMETER_UNCALIBRATED +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void - -Subscribes to only one data change of the uncalibrated acceleration sensor. - -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { + +```js +try { + sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -744,1194 +912,1450 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. console.info('Z-coordinate bias: ' + data.biasZ); } ); - ``` +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GRAVITY +### AMBIENT_LIGHT9+ -once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void +once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): void -Subscribes to only one data change of the gravity sensor. +Subscribes to data of the ambient light sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### GYROSCOPE +```js +try { + sensor.once(sensor.SensorId.AMBIENT_LIGHT, function(data) { + console.info('Illumination: ' + data.intensity); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void +### AMBIENT_TEMPERATURE9+ -Subscribes to only one data change of the gyroscope sensor. +once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the ambient temperature sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### GYROSCOPE_UNCALIBRATED +```js +try { + sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function(data) { + console.info('Temperature: ' + data.temperature); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void +### BAROMETER9+ -Subscribes to only one data change of the uncalibrated gyroscope sensor. +once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the barometer sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` -### SIGNIFICANT_MOTION +```js +try { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void +### GRAVITY9+ -Subscribes to only one data change of the significant motion sensor. +once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void + +Subscribes to data of the gravity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -### PEDOMETER_DETECTION +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void - -Subscribes to only one data change of the pedometer detection sensor. - -**Required permissions**: ohos.permission.ACTIVITY_MOTION - -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` -### PEDOMETER +```js +try { + sensor.once(sensor.SensorId.GRAVITY, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### GYROSCOPE9+ -once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void +once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): void -Subscribes to only one data change of the pedometer sensor. +Subscribes to data of the gyroscope sensor once. -**Required permissions**: ohos.permission.ACTIVITY_MOTION +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { - console.info('Steps: ' + data.steps); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -### AMBIENT_TEMPERATURE +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the ambient temperature sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_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**.| +```js +try { + sensor.once(sensor.SensorId.GYROSCOPE, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { - console.info('Temperature: ' + data.temperature); - } - ); - ``` +### GYROSCOPE_UNCALIBRATED9+ -### MAGNETIC_FIELD +once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void +Subscribes to data of the uncalibrated gyroscope sensor once. -Subscribes to only one data change of the magnetic field sensor. +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` - -### MAGNETIC_FIELD_UNCALIBRATED -once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -Subscribes to only one data change of the uncalibrated magnetic field sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` -### PROXIMITY +```js +try { + sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### HALL9+ -once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void +once(type: SensorId.HALL, callback: Callback<HallResponse>): void -Subscribes to only one data change of the proximity sensor. +Subscribes to data of the Hall effect sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { - console.info('Distance: ' + data.distance); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -### HUMIDITY +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the humidity sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_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**.| +```js +try { + sensor.once(sensor.SensorId.HALL, function(data) { + console.info('Status: ' + data.status); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { - console.info('Humidity: ' + data.humidity); - } - ); - ``` +### HEART_RATE9+ -### BAROMETER +once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void +Subscribes to data of the heart rate sensor once. -Subscribes to only one data change of the barometer sensor. +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - ); - ``` -### HALL - -once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| -Subscribes to only one data change of the Hall effect sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_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**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { - console.info('Status: ' + data.status); - } - ); - ``` -### AMBIENT_LIGHT +```js +try { + sensor.once(sensor.SensorId.HEART_BEAT_RATE, function(data) { + console.info('Heart rate: ' + data.heartRate); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### HUMIDITY9+ -once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void +once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void -Subscribes to only one data change of the ambient light sensor. +Subscribes to data of the humidity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { - console.info(' Illumination: ' + data.intensity); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -### ORIENTATION +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the orientation sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_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**.| +```js +try { + sensor.once(sensor.SensorId.HUMIDITY, function(data) { + console.info('Humidity: ' + data.humidity); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - ); - ``` +### LINEAR_ACCELEROMETER9+ -### ROTATION_VECTOR +once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void +Subscribes to data of the linear acceleration sensor once. -Subscribes to only one data change of the rotation vector sensor. +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -### HEART_RATEdeprecated +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the heart rate sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -This API is deprecated since API version 9. You are advised to use **sensor.once.HEART_BEAT_RATE9+** instead. +**Example** -**Required permissions**: ohos.permission.READ_HEALTH_DATA +```js +try { + sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**System capability**: SystemCapability.Sensors.Sensor +### MAGNETIC_FIELD9+ -**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**.| +once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { - console.info("Heart rate: " + data.heartRate); - } - ); - ``` +Subscribes to data of the magnetic field sensor once. -### HEART_BEAT_RATE9+ +**System capability**: SystemCapability.Sensors.Sensor -once(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback: Callback<HeartRateResponse>): void +**Parameters** -Subscribes to only one data change of the heart rate sensor. +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, function(data) { - console.info("Heart rate: " + data.heartRate); - } - ); - ``` -### WEAR_DETECTION +```js +try { + sensor.once(sensor.SensorId.MAGNETIC_FIELD, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void +### MAGNETIC_FIELD_UNCALIBRATED9+ -Subscribes to only one data change of the wear detection sensor. +once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>): void + +Subscribes to data of the uncalibrated magnetic field sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { - console.info("Wear status: "+ data.value); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| -## sensor.off +**Error code** -### ACCELEROMETER +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). -off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -Unsubscribes from sensor data changes. +**Example** + +```js +try { + sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### ORIENTATION9+ -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): void + +Subscribes to data of the orientation sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('x-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.ORIENTATION, function(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); ``` -### ACCELEROMETER_UNCALIBRATED +### PEDOMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void +once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the pedometer sensor once. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **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**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); +try { + sensor.once(sensor.SensorId.PEDOMETER, function(data) { + console.info('Steps: ' + data.steps); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); ``` -### AMBIENT_LIGHT +### PEDOMETER_DETECTION9+ -off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void +once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>): void -Unsubscribes from sensor data changes. +Subscribe to data of the pedometer detection sensor once. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info(' Illumination: ' + data.intensity); +try { + sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); ``` -### AMBIENT_TEMPERATURE +### PROXIMITY9+ -off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void +once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the proximity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_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 | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Temperature: ' + data.temperature); +try { + sensor.once(sensor.SensorId.PROXIMITY, function(data) { + console.info('Distance: ' + data.distance); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off( sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); ``` -### AMBIENT_TEMPERATURE +### ROTATION_VECTOR9+ -off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void +once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the rotation vector sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**.| -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Atmospheric pressure: ' + data.pressure); +try { + sensor.once(sensor.SensorId.ROTATION_VECTOR, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); ``` -### GRAVITY +### SIGNIFICANT_MOTION9+ -off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void +once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the significant motion sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); ``` -### GYROSCOPE - -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void +### WEAR_DETECTION9+ -Unsubscribes from sensor data changes. +once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the wear detection sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**.| -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + +**Error code** + +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.WEAR_DETECTION, function(data) { + console.info("Wear status: "+ data.value); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ``` -### GYROSCOPE_UNCALIBRATED +## sensor.off9+ -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void +### ACCELEROMETER9+ -Unsubscribes from sensor data changes. +off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Unsubscribes from data of the acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('x-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.ACCELEROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); ``` -### HALL +### ACCELEROMETER_UNCALIBRATED9+ -off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void +off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the uncalibrated acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| **Example** ```js -function callback(data) { - console.info('Status: ' + data.status); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); ``` -### HEART_RATEdeprecated +### AMBIENT_LIGHT9+ -off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void +off(type: SensorId.AMBIENT_LIGHT, callback?: Callback<LightResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the ambient light sensor. -This API is deprecated since API version 9. You are advised to use **sensor.off.HEART_BEAT_RATE9+** instead. +**System capability**: SystemCapability.Sensors.Sensor -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + +**Example** + +```js +try { + function callback(data) { + console.info('Illumination: ' + data.intensity); + } + sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### AMBIENT_TEMPERATURE9+ + +off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void + +Unsubscribes from data of the ambient temperature sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**.| -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| **Example** ```js -function callback(data) { - console.info("Heart rate: " + data.heartRate); +try { + function callback(data) { + console.info('Temperature: ' + data.temperature); + } + sensor.off( sensor.SensorId.AMBIENT_TEMPERATURE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback); ``` -### HEART_BEAT_RATE9+ +### BAROMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback?: Callback<HeartRateResponse>): void +off(type: SensorId.BAROMETER, callback?: Callback<BarometerResponse>): void -Unsubscribes from sensor data changes. - -**Required permissions**: ohos.permission.READ_HEALTH_DATA +Unsubscribes from data of the barometer sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**.| -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| **Example** ```js -function callback(data) { - console.info("Heart rate: " + data.heartRate); +try { + function callback(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + sensor.off(sensor.SensorId.BAROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback); ``` -### HUMIDITY +### GRAVITY9+ -off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void +off(type: SensorId.GRAVITY, callback?: Callback<GravityResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the gravity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| **Example** ```js -function callback(data) { - console.info('Humidity: ' + data.humidity); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off( sensor.SensorId.GRAVITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); ``` -### LINEAR_ACCELERATIONdeprecated - -off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void +### GYROSCOPE9+ -Unsubscribes from sensor data changes. +off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): void -This API is deprecated since API version 9. You are advised to use **sensor.off.LINEAR_ACCELEROMETER9+** instead. +Unsubscribes from data of the gyroscope sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.GYROSCOPE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); ``` -### LINEAR_ACCELEROMETER9+ +### GYROSCOPE_UNCALIBRATED9+ -off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerometerResponse>): void +off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void -Unsubscribes from sensor data changes. + Unsubscribes from data of the uncalibrated gyroscope sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GYROSCOPE_UNCALIBRATED**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback); ``` -### MAGNETIC_FIELD +### HALL9+ - off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void +off(type: SensorId.HALL, callback?: Callback<HallResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the Hall effect sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| -| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('Status: ' + data.status); + } + sensor.off(sensor.SensorId.HALL, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); ``` -### MAGNETIC_FIELD_UNCALIBRATED +### HEART_RATE9+ - off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void +off(type: SensorId.HEART_RATE, callback?: Callback<HeartRateResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the heart rate sensor. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); +try { + function callback(data) { + console.info("Heart rate: " + data.heartRate); + } + sensor.off(sensor.SensorId.HEART_RATE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); ``` -### ORIENTATION +### HUMIDITY9+ - off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void +off(type: SensorId.HUMIDITY, callback?: Callback<HumidityResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the humidity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**.| -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| **Example** ```js -function callback(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); +try { + function callback(data) { + console.info('Humidity: ' + data.humidity); + } + sensor.off(sensor.SensorId.HUMIDITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); ``` -### PEDOMETER +### LINEAR_ACCELEROMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void +off(type: SensorId.LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerometerResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the linear acceleration sensor. -**Required permissions**: ohos.permission.ACTIVITY_MOTION +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| **Example** ```js -function callback(data) { - console.info('Steps: ' + data.steps); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); ``` -### PEDOMETER_DETECTION - -off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void +### MAGNETIC_FIELD9+ -Unsubscribes from sensor data changes. +off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Unsubscribes from data of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| **Example** ```js -function callback(data) { - console.info('Scalar data: ' + data.scalar); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); ``` -### PROXIMITY +### MAGNETIC_FIELD_UNCALIBRATED9+ -off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void +off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the uncalibrated magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**.| -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| **Example** ```js -function callback(data) { - console.info('Distance: ' + data.distance); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); ``` -### ROTATION_VECTOR +### ORIENTATION9+ -off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void +off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the orientation sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); +try { + function callback(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + sensor.off(sensor.SensorId.ORIENTATION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); ``` -### SIGNIFICANT_MOTION +### PEDOMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void +off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the pedometer sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| **Example** ```js -function callback(data) { - console.info('Scalar data: ' + data.scalar); +try { + function callback(data) { + console.info('Steps: ' + data.steps); + } + sensor.off(sensor.SensorId.PEDOMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); ``` -### WEAR_DETECTION +### PEDOMETER_DETECTION9+ -off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void +off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the pedometer detection sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| **Example** ```js -function accCallback(data) { - console.info('Wear status: ' + data.value); +try { + function callback(data) { + console.info('Scalar data: ' + data.scalar); + } + sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); ``` -## sensor.transformCoordinateSystem +### PROXIMITY9+ -transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void +off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): void -Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. +Unsubscribes from data of the proximity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | ----------- | -| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| **Example** ```js -sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { - if (err) { - console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); - return; +try { + function callback(data) { + console.info('Distance: ' + data.distance); } - console.info("Operation successed. Data obtained: " + data); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + sensor.off(sensor.SensorId.PROXIMITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### ROTATION_VECTOR9+ + +off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void + +Unsubscribes from data of the rotation vector sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| + +**Example** + +```js +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); } - }) + sensor.off(sensor.SensorId.ROTATION_VECTOR, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.transformCoordinateSystem -transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> +### SIGNIFICANT_MOTION9+ -Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. +off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void + +Unsubscribes from data of the significant motion sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | -------- | -| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -**Return value** +**Example** -| Type | Description | -| ---------------------------------- | ----------- | -| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| +```js +try { + function callback(data) { + console.info('Scalar data: ' + data.scalar); + } + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### WEAR_DETECTION9+ + +off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void + +Unsubscribes from data of the wear detection sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| **Example** ```js -const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); - promise.then((data) => { - console.info("Operation successed."); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }).catch((err) => { - console.info("Operation failed"); -}) +try { + function accCallback(data) { + console.info('Wear status: ' + data.value); + } + sensor.off(sensor.SensorId.WEAR_DETECTION, accCallback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.getGeomagneticField +## sensor.getGeomagneticInfo9+ -getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void +getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** + | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | | locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | | timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| | callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getGeomagneticInfo](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** + ```js -sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { - if (err) { - console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + +try { + sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000, function(data) { + console.info('sensor_getGeomagneticInfo_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); -}); + }); +} catch (err) { + console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` -## sensor.getGeomagneticField -getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> +## sensor.getGeomagneticInfo9+ + +getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | ----------------------------------- | ---- | ----------------- | -| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | -| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| + +| 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 | -| ---------------------------------------- | ------- | + +| Type | Description | +| ---------------------------------------------------------- | -------------- | | Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getGeomagneticInfo](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** - ```js - const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); + +```js +try { + const promise = sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000); promise.then((data) => { - console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + console.info('sensor_getGeomagneticInfo_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); }).catch((reason) => { console.info('Operation failed.'); }) - ``` +} catch (err) { + console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getAltitude +## sensor.getDeviceAltitude9+ -getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void +getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. @@ -1939,28 +2363,35 @@ Obtains the altitude at which the device is located based on the sea-level atmos **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | ---- | -------------------- | -| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | -| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| -| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | +| Name | Type | Mandatory| Description | +| --------------- | --------------------------- | ---- | ------------------------------------- | +| 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. | + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getDeviceAltitude](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.getAltitude(0, 200, function(err, data) { - if (err) { - console.error( - "Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Successed to get getAltitude interface get data: " + data); +```js +try { + sensor.getDeviceAltitude(0, 200, function(data) { + console.info('Successed to get getDeviceAltitude interface get data: ' + data); }); - ``` +} catch (err) { + console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getAltitude +## sensor.getDeviceAltitude9+ -getAltitude(seaPressure: number, currentPressure: number): Promise<number> +getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<number> Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. @@ -1968,32 +2399,43 @@ Obtains the altitude at which the device is located based on the sea-level atmos **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** -| Type | Description | -| --------------------- | ------------------ | +| Type | Description | +| --------------------- | ------------------------------------ | | Promise<number> | Promise used to return the altitude, in meters.| +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getDeviceAltitude](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** - ```js - const promise = sensor.getAltitude(0, 200); +```js +try { + const promise = sensor.getDeviceAltitude (0, 200); promise.then((data) => { - console.info(' sensor_getAltitude_Promise success', data); + console.info('sensor_getDeviceAltitude_Promise success', data); }).catch((err) => { console.error("Operation failed"); }) - ``` - +} catch (err) { + console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getGeomagneticDip +## sensor.getInclination9+ -getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void +getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. @@ -2001,58 +2443,78 @@ Obtains the magnetic dip based on the inclination matrix. This API uses an async **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.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getInclination](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + - err.message); - return; - } - console.info("Successed to get getGeomagneticDip interface get data: " + data); +```js +try { + sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { + console.info('Successed to get getInclination interface get data: ' + data); }) - ``` +} catch (err) { + console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getGeomagneticDip +## sensor.getInclination9+ -getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> + getInclination(inclinationMatrix: Array<number>): Promise<number> -Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. + Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------------- | ------------------- | ---- | ------- | -| inclinationMatrix | Array<number> | Yes | Inclination matrix.| +| Name | Type | Mandatory| Description | +| ----------------- | ------------------- | ---- | -------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix.| **Return value** -| Type | Description | -| --------------------- | -------------- | +| Type | Description | +| --------------------- | ---------------------------- | | Promise<number> | Promise used to return the magnetic dip, in radians.| +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getInclination](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** - ```js - const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); +```js +try { + const promise = sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info('getGeomagneticDip_promise successed', data); + console.info('getInclination_promise successed', data); }).catch((err) => { console.error("Operation failed"); }) - ``` +} catch (err) { + console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor. getAngleModify +## sensor.getAngleVariation9+ -getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void + getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, + callback: AsyncCallback): void Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. @@ -2060,31 +2522,37 @@ Obtains the angle change between two rotation matrices. This API uses an asynchr **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.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getAngleVariation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { - if (err) { - console.error('Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } +```js +try { + sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(data) { for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } }) - ``` - +} catch (err) { + console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor. getAngleModify +## sensor.getAngleVariation9+ -getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> +getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise Obtains the angle change between two rotation matrices. This API uses a promise to return the result. @@ -2092,330 +2560,496 @@ Obtains the angle change between two rotation matrices. This API uses a promise **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 | The other rotation matrix. | **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | +| Type | Description | +| ---------------------------------- | --------------------------------- | | Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getAngleVariation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** - ```js - const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); +```js +try { + const promise = sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); promise.then((data) => { - console.info('getAngleModifiy_promise success'); for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); + console.info('data[' + i + ']: ' + data[i]); } }).catch((reason) => { - console.info("promise::catch", reason); + console.info('promise::catch ', reason); }) - ``` - +} catch (err) { + console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getRotationMatrix9+ -createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void +getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback): void -Converts a rotation vector into a rotation matrix. This API uses an asynchronous callback to return the result. +Obtains the rotation matrix from a rotation vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------- | -| 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.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } +```js +try { + sensor.getRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(data) { for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); + console.info('data[' + i + ']: ' + data[i]); } }) - ``` - +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getRotationMatrix9+ -createRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> +getRotationMatrix(rotationVector: Array<number>): Promise -Converts a rotation vector into a rotation matrix. This API uses a promise to return the result. +Obtains the rotation matrix from a rotation vector. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| **Return value** -| Type | Description | -| ---------------------------------- | ------- | +| Type | Description | +| ---------------------------------- | -------------- | | Promise<Array<number>> | Promise used to return the rotation matrix.| +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** - ```js - const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); +```js +try { + const promise = sensor.getRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { - console.info('createRotationMatrix_promise success'); for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); + console.info('data[' + i + ']: ' + data[i]); } }).catch((reason) => { - console.info("promise::catch", reason); - }) - ``` - + console.info('promise::catch ', reason); + }) +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createQuaternion +## sensor.transformRotationMatrix9+ -createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions, + callback: AsyncCallback): void -Converts a rotation vector into a quaternion. This API uses an asynchronous callback to return the result. +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | +| Name | Type | Mandatory| Description | +| ---------------- | ----------------------------------------- | ---- | ---------------------- | +| 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** +**Error code** - ```js - sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) - ``` +For details about the following error codes, see [Error Codes of sensor.transformRotationMatrix](../errorcodes/errorcode-sensor.md). +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -## sensor.createQuaternion +**Example** -createQuaternion(rotationVector: Array<number>): Promise<Array<number>> +```js +try { + sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(data) { + for (var i=0; i < data.length; i++) { + console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + } + }) +} catch (err) { + console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -Converts a rotation vector into a quaternion. This API uses a promise to return the result. +## sensor.transformRotationMatrix9+ + +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory| Description | +| ---------------- | ----------------------------------------- | ---- | ---------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<Array<number>> | Promise used to return the quaternion.| +| Type | Description | +| ---------------------------------- | ---------------------- | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| -**Example** +**Error code** - ```js - const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); - promise.then((data) => { - console.info('createQuaternion_promise successed'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((err) => { - console.info('promise failed'); - }) - ``` +For details about the following error codes, see [Error Codes of sensor.transformRotationMatrix](../errorcodes/errorcode-sensor.md). +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -## sensor.getDirection +**Example** -getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void +```js +try { + const promise = sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + promise.then((data) => { + for (var i=0; i < data.length; i++) { + console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + } + }).catch((err) => { + console.info("Operation failed"); +}) +} catch (err) { + console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. +## sensor.getQuaternion9+ + +getQuaternion(rotationVector: Array<number>, callback: AsyncCallback): void + +Obtains the quaternion from a rotation vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------------------ | -| rotationMatrix | Array<number> | Yes | Rotation matrix. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getQuaternion](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_callback" + data[i]); +```js +try { + sensor.getQuaternion ([0.20046076, 0.21907, 0.73978853, 0.60376877], function(data) { + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } }) - ``` - +} catch (err) { + console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getDirection +## sensor.getQuaternion9+ -getDirection(rotationMatrix: Array<number>): Promise<Array<number>> +getQuaternion(rotationVector: Array<number>): Promise -Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. +Obtains the quaternion from a rotation vector. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationMatrix | Array<number> | Yes | Rotation matrix.| +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | -| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| +| Type | Description | +| ---------------------------------- | ------------ | +| Promise<Array<number>> | Callback used to return the quaternion.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getQuaternion](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); +```js +try { + const promise = sensor.getQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { - console.info('sensor_getAltitude_Promise success', data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_promise" + data[i]); + console.info('getQuaternionn_promise successed'); + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } }).catch((err) => { console.info('promise failed'); }) - ``` - +} catch (err) { + console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getOrientation9+ -createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void +getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback): void -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. +Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | ------- | -| 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 | +| -------------- | ---------------------------------------- | ---- | --------------------------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getOrientation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.rotation.length; i++) { - console.info("data[" + i + "]: " + data[i]) +```js +try { + sensor.getOrientation([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { + console.info("SensorJsAPI--->Successed to get getOrientation interface get data: " + data); + for (var i = 1; i < data.length; i++) { + console.info('sensor_getOrientation_callback ' + data[i]); } }) - ``` - +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getOrientation9+ -createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> +getOrientation(rotationMatrix: Array<number>): Promise -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a promise to return the result. +Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------- | ---- | ------- | -| gravity | Array<number> | Yes | Gravity vector.| -| geomagnetic | Array<number> | Yes | Geomagnetic vector.| +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix.| **Return value** -| Type | Description | -| ---------------------------------------- | ------- | -| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| +| Type | Description | +| ---------------------------------- | --------------------------------- | +| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getOrientation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); +```js +try { + const promise = sensor.getOrientation([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info('createRotationMatrix_promise successed'); - for (var i=0; i < data.rotation.length; i++) { - console.info("data[" + i + "]: " + data[i]); + console.info('sensor_getOrientation_Promise success', data); + for (var i = 1; i < data.length; i++) { + console.info('sensor_getOrientation_promise ' + data[i]); } }).catch((err) => { console.info('promise failed'); }) - ``` +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getSensorLists9+ +## sensor.getRotationMatrix9+ - getSensorLists(callback: AsyncCallback): void +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void -Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. +Obtains the rotation matrix based on a gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback | Yes | Callback used to return the sensor list.| +| 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** +**Error code** -```js -sensor.getSensorList((error, data) => { - if (error) { - console.error('getSensorList failed'); - } else { - console.info("getSensorList callback in" + data.length); - for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); - } - } -}); -``` +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). -## sensor.getSensorLists9+ +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | - getSensorLists(): Promise< Array<Sensor>> +**Example** + +```js +try { + sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(data) { + console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); + }) +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getRotationMatrix9+ + +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> + +Obtains the rotation matrix based on a gravity vector and geomagnetic vector. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------- | ---- | -------------- | +| gravity | Array<number> | Yes | Gravity vector.| +| geomagnetic | Array<number> | Yes | Geomagnetic vector.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + const promise = sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); + promise.then((data) => { + console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); + }).catch((err) => { + console.info('promise failed'); + }) +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getSensorList9+ + + getSensorList(callback: AsyncCallback): void + +Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ---------------- | +| callback | AsyncCallback | Yes | Callback used to return the sensor list.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSensorList](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.getSensorList((data) => { + console.info('getSensorList callback in ' + data.length); + for (var i = 0; i < data.length; i++) { + console.info("getSensorList " + JSON.stringify(data[i])); + } + }); +} catch (err) { + console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getSensorList9+ + + getSensorList(): Promise< Array<Sensor>> Obtains information about all sensors on the device. This API uses a promise to return the result. @@ -2423,26 +3057,38 @@ Obtains information about all sensors on the device. This API uses a promise to **Return value** -| Name | Type | Mandatory| Description | -| ------- | --------------------------------------- | ---- | ---------------- | -| promise | Promise | Yes | Promise used to return the sensor list.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ---------------- | +| promise | Promise | Yes | Promise used to return the sensor list.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSensorList](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSensorList().then((data) => { - console.info("getSensorList promise in" + data.length); - for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); - } -}, (error)=>{ - console.error('getSensorList failed'); -}); +try { + sensor.getSensorList().then((data) => { + console.info('getSensorList promise in ' + data.length); + for (var i = 0; i < data.length; i++) { + console.info("getSensorList " + JSON.stringify(data[i])); + } + }, (error)=>{ + console.error('getSensorList failed'); + }); +} catch (err) { + console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` ## sensor.getSingleSensor9+ -getSingleSensor(type: SensorType, callback: AsyncCallback<sensor>): void +getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void Obtains information about the sensor of a specific type. This API uses an asynchronous callback to return the result. @@ -2450,26 +3096,34 @@ Obtains information about the sensor of a specific type. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ---------------- | -| type | SensorType | Yes | Sensor type. | -| callback | AsyncCallback<[Sensor](#sensor)> | Yes | Callback used to return the sensor information.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------------- | +| type | [SensorId](#sensorid9) | Yes | Sensor type. | +| callback | AsyncCallback<[Sensor](#sensor9)> | Yes | Callback used to return the sensor information.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSingleSensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js - sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { - if (error) { - console.error('getSingleSensor failed'); - } else { - console.info("getSingleSensor " + JSON.stringify(data)); - } -}); +try { + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { + console.info('getSingleSensor ' + JSON.stringify(data)); + }); +} catch (err) { + console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` ## sensor.getSingleSensor9+ - getSingleSensor(type: SensorType,): Promise<Sensor> + getSingleSensor(type: SensorId): Promise<Sensor> Obtains information about the sensor of a specific type. This API uses a promise to return the result. @@ -2477,58 +3131,98 @@ Obtains information about the sensor of a specific type. This API uses a promise **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------ | -| type | SensorType | Yes | Sensor type.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------ | +| type | [SensorId](#sensorid9) | Yes | Sensor type.| **Return value** -| Name | Type | Mandatory| Description | -| ------- | -------------------------------- | ---- | ---------------- | -| promise | Promise<[Sensor](#sensor)> | Yes | Promise used to return the sensor information.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------- | ---- | ---------------- | +| promise | Promise<[Sensor](#sensor9)> | Yes | Promise used to return the sensor information.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSingleSensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { - console.info("getSingleSensor " + JSON.stringify(data)); -}, (error)=>{ - console.error('getSingleSensor failed'); -}); +try { + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { + console.info('getSingleSensor '+ JSON.stringify(data)); + }, (error)=>{ + console.error('getSingleSensor failed'); + }); +} catch (err) { + console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` -## SensorType +## SensorId9+ + +Enumerates the sensor types. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Default Value| Description | +| --------------------------- | ------ | ---------------------- | +| ACCELEROMETER | 1 | Acceleration sensor. | +| GYROSCOPE | 2 | Gyroscope sensor. | +| AMBIENT_LIGHT | 5 | Ambient light sensor. | +| MAGNETIC_FIELD | 6 | Magnetic field sensor. | +| BAROMETER | 8 | Barometer sensor. | +| HALL | 10 | Hall effect sensor. | +| PROXIMITY | 12 | Proximity sensor. | +| HUMIDITY | 13 | Humidity sensor. | +| ORIENTATION | 256 | Orientation sensor. | +| GRAVITY | 257 | Gravity sensor. | +| LINEAR_ACCELEROMETER | 258 | Linear acceleration sensor. | +| ROTATION_VECTOR | 259 | Rotation vector sensor. | +| AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | +| MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | +| GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | +| SIGNIFICANT_MOTION | 264 | Significant motion sensor. | +| PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | +| PEDOMETER | 266 | Pedometer sensor. | +| HEART_RATE | 278 | Heart rate sensor. | +| WEAR_DETECTION | 280 | Wear detection sensor. | +| ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| + +## SensorType(deprecated) Enumerates the sensor types. **System capability**: SystemCapability.Sensors.Sensor -| Name | Default Value | Description | -| ---------------------------------------- | ---- | ----------- | -| SENSOR_TYPE_ID_ACCELEROMETER | 1 | Acceleration sensor. | -| SENSOR_TYPE_ID_GYROSCOPE | 2 | Gyroscope sensor. | -| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | Ambient light sensor. | -| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | Magnetic field sensor. | -| SENSOR_TYPE_ID_BAROMETER | 8 | Barometer sensor. | -| SENSOR_TYPE_ID_HALL | 10 | Hall effect sensor. | -| SENSOR_TYPE_ID_PROXIMITY | 12 | Proximity sensor. | -| SENSOR_TYPE_ID_HUMIDITY | 13 | Humidity sensor. | -| SENSOR_TYPE_ID_ORIENTATION | 256 | Orientation sensor. | -| SENSOR_TYPE_ID_GRAVITY | 257 | Gravity sensor. | -| SENSOR_TYPE_ID_LINEAR_ACCELERATIONdeprecated | 258 | Linear acceleration sensor. | -| SENSOR_TYPE_ID_LINEAR_ACCELEROMETER | 258 | Linear acceleration sensor. | -| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | Rotation vector sensor. | -| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | -| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | -| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | -| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | Significant motion sensor. | -| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | -| SENSOR_TYPE_ID_PEDOMETER | 266 | Pedometer sensor. | -| SENSOR_TYPE_ID_HEART_RATEdeprecated | 278 | Heart rate sensor. | -| SENSOR_TYPE_ID_HEART_BEAT_RATE | 278 | Heart rate sensor. | -| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | Wear detection sensor. | -| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| +| Name | Default Value| Description | +| ------------------------------------------ | ------ | ---------------------- | +| SENSOR_TYPE_ID_ACCELEROMETER | 1 | Acceleration sensor. | +| SENSOR_TYPE_ID_GYROSCOPE | 2 | Gyroscope sensor. | +| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | Ambient light sensor. | +| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | Magnetic field sensor. | +| SENSOR_TYPE_ID_BAROMETER | 8 | Barometer sensor. | +| SENSOR_TYPE_ID_HALL | 10 | Hall effect sensor. | +| SENSOR_TYPE_ID_PROXIMITY | 12 | Proximity sensor. | +| SENSOR_TYPE_ID_HUMIDITY | 13 | Humidity sensor. | +| SENSOR_TYPE_ID_ORIENTATION | 256 | Orientation sensor. | +| SENSOR_TYPE_ID_GRAVITY | 257 | Gravity sensor. | +| SENSOR_TYPE_ID_LINEAR_ACCELERATION | 258 | Linear acceleration sensor. | +| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | Rotation vector sensor. | +| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | +| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | +| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | +| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | Significant motion sensor. | +| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | +| SENSOR_TYPE_ID_PEDOMETER | 266 | Pedometer sensor. | +| SENSOR_TYPE_ID_HEART_RATE | 278 | Heart rate sensor. | +| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | Wear detection sensor. | +| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| ## Response @@ -2541,7 +3235,7 @@ Describes the timestamp of the sensor data. | --------- | -------- | ---- | ---- | ------------------------ | | timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| -## Sensor +## Sensor9+ Describes the sensor information. @@ -2553,8 +3247,10 @@ Describes the sensor information. | venderName | string | Vendor of the sensor. | | firmwareVersion | string | Firmware version of the sensor. | | hardwareVersion | string | Hardware version of the sensor. | -| sensorTypeId | number | Sensor type ID. | +| sensorId | number | Sensor type ID. | | maxRange | number | Maximum measurement range of the sensor.| +| minSamplePeriod | number | Minimum sampling period. | +| maxSamplePeriod | number | Maximum sampling period. | | precision | number | Precision of the sensor. | | power | number | Power supply of the sensor. | @@ -2565,11 +3261,11 @@ Describes the acceleration sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ---------------------- | -| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ------------------------------------ | +| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| ## LinearAccelerometerResponse @@ -2579,11 +3275,11 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------------------- | +| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| ## AccelerometerUncalibratedResponse @@ -2593,14 +3289,14 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ---------------------------- | -| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | -| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | -| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | -| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | -| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| -| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------------ | +| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | +| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | +| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | +| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | +| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| +| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | ## GravityResponse @@ -2610,11 +3306,11 @@ Describes the gravity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------------------- | +| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| ## OrientationResponse @@ -2624,11 +3320,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ----------------- | -| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| -| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| -| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | --------------------------------- | +| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| ## RotationVectorResponse @@ -2638,12 +3334,12 @@ Describes the rotation vector sensor data. It extends from [Response](#response) **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | --------- | -| x | number | Yes | Yes | X-component of the rotation vector.| -| y | number | Yes | Yes | Y-component of the rotation vector.| -| z | number | Yes | Yes | Z-component of the rotation vector.| -| w | number | Yes | Yes | Scalar. | +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ----------------- | +| x | number | Yes | Yes | X-component of the rotation vector.| +| y | number | Yes | Yes | Y-component of the rotation vector.| +| z | number | Yes | Yes | Z-component of the rotation vector.| +| w | number | Yes | Yes | Scalar. | ## GyroscopeResponse @@ -2653,11 +3349,11 @@ Describes the gyroscope sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------- | -| x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s.| -| y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s.| -| z | number | Yes | Yes | Angular velocity of rotation around the z-axis of the device, in rad/s.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | -------------------------------- | +| x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s.| +| y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s.| +| z | number | Yes | Yes | Angular velocity of rotation around the z-axis of the device, in rad/s.| ## GyroscopeUncalibratedResponse @@ -2667,14 +3363,14 @@ Describes the uncalibrated gyroscope sensor data. It extends from [Response](#re **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | -| y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | -| z | number | Yes | Yes | Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s. | -| biasX | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| -| biasY | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| -| biasZ | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------ | +| x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | +| y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | +| z | number | Yes | Yes | Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s. | +| biasX | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| +| biasY | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| +| biasZ | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| ## SignificantMotionResponse @@ -2684,9 +3380,9 @@ Describes the significant motion sensor data. It extends from [Response](#respon **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | -| scalar | number | Yes | Yes | Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| scalar | number | Yes | Yes | Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| ## ProximityResponse @@ -2696,9 +3392,9 @@ Describes the proximity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ---------------------------- | -| distance | number | Yes | Yes | Proximity between the visible object and the device monitor. The value **0** means the two are close to each other, and **1** means that they are far away from each other.| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | ------------------------------------------------------ | +| distance | number | Yes | Yes | Proximity between the visible object and the device monitor. The value **0** means the two are close to each other, and **1** means that they are far away from each other.| ## LightResponse @@ -2708,9 +3404,9 @@ Describes the ambient light sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ----------- | -| intensity | number | Yes | Yes | Illumination, in lux.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ---------------------- | +| intensity | number | Yes | Yes | Illumination, in lux.| ## HallResponse @@ -2746,14 +3442,14 @@ Describes the uncalibrated magnetic field sensor data. It extends from [Response **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ---------------------- | -| x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | -| y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | -| z | number | Yes | Yes | Uncalibrated magnetic field strength on the z-axis, in μT. | -| biasX | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| -| biasY | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| -| biasZ | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | -------------------------------------- | +| x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | +| y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | +| z | number | Yes | Yes | Uncalibrated magnetic field strength on the z-axis, in μT. | +| biasX | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| +| biasY | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| +| biasZ | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| ## PedometerResponse @@ -2763,9 +3459,9 @@ Describes the pedometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | -------- | -| steps | number | Yes | Yes | Number of steps a user has walked.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ---------------- | +| steps | number | Yes | Yes | Number of steps a user has walked.| ## HumidityResponse @@ -2775,9 +3471,9 @@ Describes the humidity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ------------------------------------ | -| humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | --------------------------------------------------------- | +| humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| ## PedometerDetectionResponse @@ -2787,9 +3483,9 @@ Describes the pedometer detection sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | -| scalar | number | Yes | Yes | Pedometer detection. This parameter specifies whether a user takes a step. The value **0** means that the user does not take a step, and **1** means that the user takes a step.| +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| scalar | number | Yes | Yes | Pedometer detection. This parameter specifies whether a user takes a step. The value **0** means that the user does not take a step, and **1** means that the user takes a step.| ## AmbientTemperatureResponse @@ -2799,9 +3495,9 @@ Describes the ambient temperature sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----------- | ------ | ---- | ---- | ------------- | -| temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| +| Name | Type| Readable| Writable| Description | +| ----------- | -------- | ---- | ---- | -------------------------- | +| temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| ## BarometerResponse @@ -2811,9 +3507,9 @@ Describes the barometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ------------ | -| pressure | number | Yes | Yes | Atmospheric pressure, in pascal.| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | ------------------------ | +| pressure | number | Yes | Yes | Atmospheric pressure, in pascal.| ## HeartRateResponse @@ -2823,9 +3519,9 @@ Describes the heart rate sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | --------------------- | -| heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | --------------------------------------- | +| heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| ## WearDetectionResponse @@ -2835,9 +3531,9 @@ Describes the wear detection sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------- | -| value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------------ | +| value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| ## Options @@ -2846,9 +3542,9 @@ Describes the sensor data reporting frequency. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Description | -| -------- | ------ | --------------------------- | -| interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| +| Name | Type| Description | +| -------- | -------- | ------------------------------------------- | +| interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| ## RotationMatrixResponse @@ -2856,10 +3552,10 @@ Describes the response for setting the rotation matrix. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----------- | ------------------- | ---- | ---- | ----- | -| rotation | Array<number> | Yes | Yes | Rotation matrix.| -| inclination | Array<number> | Yes | Yes | Inclination matrix.| +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------- | ---- | ---- | ---------- | +| rotation | Array<number> | Yes | Yes | Rotation matrix.| +| inclination | Array<number> | Yes | Yes | Inclination matrix.| ## CoordinatesOptions @@ -2868,10 +3564,10 @@ Describes the coordinate options. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------ | -| x | number | Yes | Yes | X coordinate direction.| -| y | number | Yes | Yes | Y coordinate direction.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ----------- | +| x | number | Yes | Yes | X coordinate direction.| +| y | number | Yes | Yes | Y coordinate direction.| ## GeomagneticResponse @@ -2880,15 +3576,15 @@ Describes a geomagnetic response object. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------------- | ------ | ---- | ---- | ------------------------- | -| x | number | Yes | Yes | North component of the geomagnetic field. | -| y | number | Yes | Yes | East component of the geomagnetic field. | -| z | number | Yes | Yes | Vertical component of the geomagnetic field. | -| geomagneticDip | number | Yes | Yes | Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector. | -| deflectionAngle | number | Yes | Yes | Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| -| levelIntensity | number | Yes | Yes | Horizontal intensity of the magnetic field vector field. | -| totalIntensity | number | Yes | Yes | Total intensity of the magnetic field vector. | +| Name | Type| Readable| Writable| Description | +| --------------- | -------- | ---- | ---- | -------------------------------------------------- | +| x | number | Yes | Yes | North component of the geomagnetic field. | +| y | number | Yes | Yes | East component of the geomagnetic field. | +| z | number | Yes | Yes | Vertical component of the geomagnetic field. | +| geomagneticDip | number | Yes | Yes | Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector. | +| deflectionAngle | number | Yes | Yes | Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| +| levelIntensity | number | Yes | Yes | Horizontal intensity of the magnetic field vector field. | +| totalIntensity | number | Yes | Yes | Total intensity of the magnetic field vector. | ## LocationOptions @@ -2896,8 +3592,2346 @@ Describes the geographical location. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ----- | -| latitude | number | Yes | Yes | Latitude. | -| longitude | number | Yes | Yes | Longitude. | -| altitude | number | Yes | Yes | Altitude.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ---------- | +| latitude | number | Yes | Yes | Latitude. | +| longitude | number | Yes | Yes | Longitude. | +| altitude | number | Yes | Yes | Altitude.| + +## sensor.on(deprecated) + +### ACCELEROMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void + +Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ACCELEROMETER](#accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### LINEAR_ACCELERATION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void + +Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void + +Subscribes to data changes of the uncalibrated acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + ``` + +### GRAVITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void + +Subscribes to data changes of the gravity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GRAVITY](#gravity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### GYROSCOPE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void + +Subscribes to data changes of the gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GYROSCOPE](#gyroscope9) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void + +Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + ``` + +### SIGNIFICANT_MOTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void + +Subscribes to data changes of the significant motion sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.SIGNIFICANT_MOTION](#significant_motion9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, + {interval: 10000000} + ); + ``` + +### PEDOMETER_DETECTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void + +Subscribes to data changes of the pedometer detection sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PEDOMETER_DETECTION](#pedometer_detection9) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, + {interval: 10000000} + ); + ``` + +### PEDOMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void + +Subscribes to data changes of the pedometer sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PEDOMETER](#pedometer9) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ + console.info('Steps: ' + data.steps); + }, + {interval: 10000000} + ); + ``` + +### AMBIENT_TEMPERATURE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void + +Subscribes to data changes of the ambient temperature sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.AMBIENT_TEMPERATURE](#ambient_temperature9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ + console.info('Temperature: ' + data.temperature); + }, + {interval: 10000000} + ); + ``` + +### MAGNETIC_FIELD(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void + +Subscribes to data changes of the magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.MAGNETIC_FIELD](#magnetic_field9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void + +Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + ``` + +### PROXIMITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void + +Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PROXIMITY](#proximity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ + console.info('Distance: ' + data.distance); + }, + {interval: 10000000} + ); + ``` + +### HUMIDITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void + +Subscribes to data changes of the humidity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HUMIDITY](#humidity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ + console.info('Humidity: ' + data.humidity); + }, + {interval: 10000000} + ); + ``` + +### BAROMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void + +Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.BAROMETER](#barometer9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ + console.info('Atmospheric pressure: ' + data.pressure); + }, + {interval: 10000000} + ); + ``` + +### HALL(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void + +Subscribes to data changes of the Hall effect sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HALL](#hall9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ + console.info('Status: ' + data.status); + }, + {interval: 10000000} + ); + ``` + +### AMBIENT_LIGHT(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void + +Subscribes to data changes of the ambient light sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.AMBIENT_LIGHT](#ambient_light9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ + console.info(' Illumination: ' + data.intensity); + }, + {interval: 10000000} + ); + ``` + +### ORIENTATION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void + +Subscribes to data changes of the orientation sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ORIENTATION](#orientation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }, + {interval: 10000000} + ); + ``` + +### HEART_RATE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void + +Subscribes to only one data change of the heart rate sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HEART_RATE](#heart_rate9) instead. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### ROTATION_VECTOR(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void + +Subscribes to data changes of the rotation vector sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ROTATION_VECTOR](#rotation_vector9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, + {interval: 10000000} + ); + ``` + +### WEAR_DETECTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void + +Subscribes to data changes of the wear detection sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.WEAR_DETECTION](#wear_detection9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ + console.info('Wear status: ' + data.value); + }, + {interval: 10000000} + ); + ``` + +## sensor.once(deprecated) + +### ACCELEROMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void + +Subscribes to only one data change of the acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ACCELEROMETER](#accelerometer9-1) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + +### LINEAR_ACCELERATION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void + +Subscribes to only one data change of the linear acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9-1) instead. + +**Required permissions**: ohos.permission.ACCELERATION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9-1) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | + +**Example** + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + +### GRAVITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void + +Subscribes to only one data change of the gravity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GRAVITY](#gravity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + +### GYROSCOPE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void + +Subscribes to only one data change of the gyroscope sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GYROSCOPE](#gyroscope9-1) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated gyroscope sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9-1) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + +### SIGNIFICANT_MOTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void + +Subscribes to only one data change of the significant motion sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.SIGNIFICANT_MOTION](#significant_motion9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); + ``` + +### PEDOMETER_DETECTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void + +Subscribes to only one data change of the pedometer detection sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PEDOMETER_DETECTION](#pedometer_detection9-1) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); + ``` + +### PEDOMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void + +Subscribes to only one data change of the pedometer sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PEDOMETER](#pedometer9-1) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { + console.info('Steps: ' + data.steps); + } + ); + ``` + +### AMBIENT_TEMPERATURE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void + +Subscribes to only one data change of the ambient temperature sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.AMBIENT_TEMPERATURE](#ambient_temperature9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { + console.info('Temperature: ' + data.temperature); + } + ); + ``` + +### MAGNETIC_FIELD(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void + +Subscribes to only one data change of the magnetic field sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.MAGNETIC_FIELD](#magnetic_field9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated magnetic field sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + +### PROXIMITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void + +Subscribes to only one data change of the proximity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PROXIMITY](#proximity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { + console.info('Distance: ' + data.distance); + } + ); + ``` + +### HUMIDITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void + +Subscribes to only one data change of the humidity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HUMIDITY](#humidity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { + console.info('Humidity: ' + data.humidity); + } + ); + ``` + +### BAROMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void + +Subscribes to only one data change of the barometer sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.BAROMETER](#barometer9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + ); + ``` + +### HALL(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void + +Subscribes to only one data change of the Hall effect sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HALL](#hall9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { + console.info('Status: ' + data.status); + } + ); + ``` + +### AMBIENT_LIGHT(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void + +Subscribes to only one data change of the ambient light sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.AMBIENT_LIGHT](#ambient_light9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { + console.info(' Illumination: ' + data.intensity); + } + ); + ``` + +### ORIENTATION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void + +Subscribes to only one data change of the orientation sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ORIENTATION](#orientation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + ); + ``` + +### ROTATION_VECTOR(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void + +Subscribes to only one data change of the rotation vector sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ROTATION_VECTOR](#rotation_vector9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + ); + ``` + +### HEART_RATE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void + +Subscribes to only one data change of the heart rate sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HEART_RATE](#heart_rate9-1) instead. + +**Required permissions**: ohos.permission.HEART_RATE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### WEAR_DETECTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void + +Subscribes to only one data change of the wear detection sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.WEAR_DETECTION](#wear_detection9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | + +**Example** + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { + console.info("Wear status: "+ data.value); + } + ); + ``` + +## sensor.off(deprecated) + +### ACCELEROMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ACCELEROMETER](#accelerometer9-2) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('x-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); +``` + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9-2) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); +``` + +### AMBIENT_LIGHT(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.AMBIENT_LIGHT](#ambient_light9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | + +**Example** + +```js +function callback(data) { + console.info(' Illumination: ' + data.intensity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); +``` + +### AMBIENT_TEMPERATURE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.AMBIENT_TEMPERATURE](#ambient_temperature9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Temperature: ' + data.temperature); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); +``` + +### BAROMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.BAROMETER](#barometer9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Atmospheric pressure: ' + data.pressure); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); +``` + +### GRAVITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GRAVITY](#gravity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); +``` + +### GYROSCOPE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GYROSCOPE](#gyroscope9-2) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); +``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9-2) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); +``` + +### HALL(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HALL](#hall9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Status: ' + data.status); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); +``` + +### HEART_RATE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HEART_RATE](#heart_rate9-2) instead. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### HUMIDITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HUMIDITY](#humidity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Humidity: ' + data.humidity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); +``` + +### LINEAR_ACCELERATION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9-2) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_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**. | + +### MAGNETIC_FIELD(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.MAGNETIC_FIELD](#magnetic_field9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); +``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); +``` + +### ORIENTATION(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ORIENTATION](#orientation9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | + +**Example** + +```js +function callback(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); +``` + +### PEDOMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PEDOMETER](#pedometer9-2) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Steps: ' + data.steps); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); +``` + +### PEDOMETER_DETECTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PEDOMETER_DETECTION](#pedometer_detection9-2) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); +``` + +### PROXIMITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PROXIMITY](#proximity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Distance: ' + data.distance); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); +``` + +### ROTATION_VECTOR(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ROTATION_VECTOR](#rotation_vector9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); +``` + +### SIGNIFICANT_MOTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.SIGNIFICANT_MOTION](#significant_motion9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); +``` + +### WEAR_DETECTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.WEAR_DETECTION](#wear_detection9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | + +**Example** + +```js +function accCallback(data) { + console.info('Wear status: ' + data.value); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); +``` + +## sensor.transformCoordinateSystem(deprecated) + +transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.transformRotationMatrix](#sensortransformrotationmatrix9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ----------------------------------------- | --------- | ------------------------------------------------------------ | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated. | + +**Example** + +```js +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { + if (err) { + console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); + return; + } + console.info("Operation successed. Data obtained: " + data); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }) +``` +## sensor.transformCoordinateSystem(deprecated) + +transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.transformRotationMatrix](#sensortransformrotationmatrix9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ----------------------------------------- | --------- | ----------------------------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated. | + +**Example** + +```js +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + promise.then((data) => { + console.info("Operation successed."); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }).catch((err) => { + console.info("Operation failed"); +}) +``` + +## sensor.getGeomagneticField(deprecated) + +getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void + +Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getGeomagneticInfo](#sensorgetgeomagneticinfo9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds. | +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | + +**Example** +```js +sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { + if (err) { + console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); +}); +``` +## sensor.getGeomagneticField(deprecated) + +getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> + +Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getGeomagneticInfo](#sensorgetgeomagneticinfo9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ----------------------------------- | --------- | ------------------------------------------------------------ | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------------- | --------------------------------------------- | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | + +**Example** + ```js + const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); + promise.then((data) => { + console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + }).catch((reason) => { + console.info('Operation failed.'); + }) + ``` + +## sensor.getAltitude(deprecated) + +getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getDeviceAltitude](#sensorgetdevicealtitude9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa. | +| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | + +**Example** + + ```js + sensor.getAltitude(0, 200, function(err, data) { + if (err) { + console.error( + "Operation failed. Error code: " + err.code + ", message: " + err.message); + return; + } + console.info("Successed to get getAltitude interface get data: " + data); + }); + ``` + +## sensor.getAltitude(deprecated) + +getAltitude(seaPressure: number, currentPressure: number): Promise<number> + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getDeviceAltitude](#sensorgetdevicealtitude9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ------ | --------- | ------------------------------------------------------------ | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------- | +| Promise<number> | Promise used to return the altitude, in meters. | + +**Example** + + ```js + const promise = sensor.getAltitude(0, 200); + promise.then((data) => { + console.info(' sensor_getAltitude_Promise success', data); + }).catch((err) => { + console.error("Operation failed"); + }) + ``` + + +## sensor.getGeomagneticDip(deprecated) + +getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void + +Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getInclination](#sensorgetinclination9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------------- | --------------------------- | --------- | ----------------------------------------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | +| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians. | + +**Example** + + ```js + sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + + err.message); + return; + } + console.info("Successed to get getGeomagneticDip interface get data: " + data); + }) + ``` + +## sensor.getGeomagneticDip(deprecated) + +getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> + +Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getInclination](#sensorgetinclination9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------------- | ------------------- | --------- | ------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------------------------- | +| Promise<number> | Promise used to return the magnetic dip, in radians. | + +**Example** + + ```js + const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('getGeomagneticDip_promise successed', data); + }).catch((err) => { + console.error("Operation failed"); + }) + ``` + +## sensor. getAngleModify(deprecated) + +getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void + +Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getAngleVariation](#sensorgetanglevariation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes. | + +**Example** + + ```js + sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { + if (err) { + console.error('Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + ``` + + +## sensor. getAngleModify(deprecated) + +getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> + +Obtains the angle change between two rotation matrices. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getAngleVariation](#sensorgetanglevariation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------------- | ------------------- | --------- | -------------------------- | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes. | + +**Example** + + ```js + const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); + promise.then((data) => { + console.info('getAngleModifiy_promise success'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((reason) => { + console.info("promise::catch", reason); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + +Converts a rotation vector into a rotation matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | -------------------------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix. | + +**Example** + + ```js + sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> + +Converts a rotation vector into a rotation matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | --------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------- | +| Promise<Array<number>> | Promise used to return the rotation matrix. | + +**Example** + + ```js + const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('createRotationMatrix_promise success'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((reason) => { + console.info("promise::catch", reason); + }) + ``` + + +## sensor.createQuaternion(deprecated) + +createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + +Converts a rotation vector into a quaternion. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getQuaternion](#sensorgetquaternion9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | --------------------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | + +**Example** + + ```js + sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + ``` + + +## sensor.createQuaternion(deprecated) + +createQuaternion(rotationVector: Array<number>): Promise<Array<number>> + +Converts a rotation vector into a quaternion. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getQuaternion](#sensorgetquaternion9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | --------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | + +**Return value** + +| Type | Description | +| ---------------------------------- | -------------------------------------- | +| Promise<Array<number>> | Promise used to return the quaternion. | + +**Example** + + ```js + const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('createQuaternion_promise successed'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + +## sensor.getDirection(deprecated) + +getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void + +Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getOrientation](#sensorgetorientation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes. | + +**Example** + + ```js + sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); + for (var i = 1; i < data.length; i++) { + console.info("sensor_getDirection_callback" + data[i]); + } + }) + ``` + + +## sensor.getDirection(deprecated) + +getDirection(rotationMatrix: Array<number>): Promise<Array<number>> + +Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getOrientation](#sensorgetorientation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | ---------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes. | + +**Example** + + ```js + const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('sensor_getAltitude_Promise success', data); + for (var i = 1; i < data.length; i++) { + console.info("sensor_getDirection_promise" + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void + +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------------------------------------ | --------- | -------------------------------------------- | +| gravity | Array<number> | Yes | Gravity vector. | +| geomagnetic | Array<number> | Yes | Geomagnetic vector. | +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix. | + +**Example** + + ```js + sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { + if (err) { + console.error('error code is: ' + err.code + ', message: ' + err.message); + return; + } + console.info(JSON.stringify(data)); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> + +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-3) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | --------- | ------------------- | +| gravity | Array<number> | Yes | Gravity vector. | +| geomagnetic | Array<number> | Yes | Geomagnetic vector. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------- | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix. | + +**Example** + + ```js + const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); + promise.then((data) => { + console.info(JSON.stringify(data)); + }).catch((err) => { + console.info('promise failed'); + }) + ``` 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 7ed184b2a61aaaf781a37b9137e8f510a2ffbc2f..f05be876284c617ecb72b9c9c6ed9bffe0c05cd1 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 @@ -6,8 +6,8 @@ You can use the APIs of this module to start, terminate, connect, and disconnect > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module can be used only in the stage model. ## Usage diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 3cb8380f9f35b7fa584f09b0d88c5fb45e0c22fe..9474b7a298b40546ae1b5fe1a7c639efb1195de3 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,21 +1,479 @@ # Settings -The **Settings** module provides APIs for setting data items. +The **settings** module provides APIs for setting data items. > **NOTE** -> -> The initial APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - +> +> The initial APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```ts +```js import settings from '@ohos.settings'; ``` +## date + +Provides data items for setting the time and date formats. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| DATE_FORMAT | string | Yes | Yes | Date format.
The value can be **mm/dd/yyyy**, **dd/mm/yyyy**, or **yyyy/mm/dd**, where **mm** indicates the month, **dd** indicates the day, and **yyyy** indicates the year.| +| TIME_FORMAT | string | Yes | Yes | Time format.
**12**: 12-hour format.
**24**: 24-hour format.| +| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
The value **true** means that the date, time, and time zone are automatically obtained from NITZ; and **false** means the opposite.| +| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.
The value **true** means that the time zone is automatically obtained from NITZ; and **false** means the opposite.| + +## display + +Provides data items for setting the display effects. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| ----------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| FONT_SCALE | string | Yes | Yes | Scale factor of the font. The value is a floating point number. | +| SCREEN_BRIGHTNESS_STATUS | string | Yes | Yes | Screen brightness. The value ranges from 0 to 255. | +| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.
**AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.
**MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled.| +| AUTO_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is enabled. | +| MANUAL_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is disabled. | +| SCREEN_OFF_TIMEOUT | string | Yes | Yes | Waiting time for the device to enter the sleep state when not in use (unit: ms). | +| DEFAULT_SCREEN_ROTATION | string | Yes | Yes | Rotation angle. This attribute is valid only when screen auto-rotation is disabled.
**0**: The screen rotates by 0 degrees.
**1**: The screen rotates by 90 degrees.
**2**: The screen rotates by 180 degrees.
**3**: The screen rotates by 270 degrees.| +| ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration. This affects the start delay and duration of all such animations.
If the value is **0**, the animation ends immediately. The default value is **1**.| +| TRANSITION_ANIMATION_SCALE | string | Yes | Yes | Scale factor for transition animations.
The value **0** indicates that the transition animations are disabled. | +| WINDOW_ANIMATION_SCALE | string | Yes | Yes | Scale factor for normal window animations.
The value **0** indicates that window animations are disabled. | +| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.
**1**: Display color inversion is enabled.
**0**: Display color inversion is disabled.| + +## general + +Provides data items for setting the general information about the device. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| -------------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| SETUP_WIZARD_FINISHED | string | Yes | Yes | Whether the startup wizard is running.
If the value is **0**, the startup wizard is not running.
If the value is not **0**, the startup wizard is running.| +| END_BUTTON_ACTION | string | Yes | Yes | Action after the call end button is pressed if the user is not in a call.
**0**: Nothing happens.
**1**: The home screen is displayed.
**2**: The device enters sleep mode and the screen is locked.
**3**: The home screen is displayed. If the focus is already on the home screen, the device will enter sleep mode.| +| ACCELEROMETER_ROTATION_STATUS | string | Yes | Yes | Whether the accelerometer is used to change screen orientation, that is, whether to enable auto-rotation.
**1**: The accelerometer is used.
**0**: The accelerometer is not used.| +| AIRPLANE_MODE_STATUS | string | Yes | Yes | Whether airplane mode is enabled.
**1**: Airplane mode is enabled.
**0**: Airplane mode is disabled.| +| DEVICE_PROVISION_STATUS | string | Yes | Yes | Whether the device is preconfigured.
On a multi-user device with a single system user, the screen may be locked when the value is **true**. In addition, other features cannot be started on the system user unless they are marked to display on the lock screen.| +| HDC_STATUS | string | Yes | Yes | Whether the hard disk controller (HDC) on the USB device is enabled.
**true**: HDC is enabled.
**false**: HDC is disabled.| +| BOOT_COUNTING | string | Yes | Yes | Number of boot operations after the device is powered on. | +| CONTACT_METADATA_SYNC_STATUS | string | Yes | Yes | Whether contacts metadata synchronization is enabled.
**true**: Contacts metadata synchronization is enabled.
**false**: Contacts metadata synchronization is disabled.| +| DEVELOPMENT_SETTINGS_STATUS | string | Yes | Yes | Whether developer options are enabled.
**true**: Developer options are enabled.
**false**: Developer options are disabled.| +| DEVICE_NAME | string | Yes | Yes | Device name. | +| USB_STORAGE_STATUS | string | Yes | Yes | Whether USB mass storage is enabled.
**true**: USB mass storage is enabled.
**false**: USB mass storage is disabled.| +| DEBUGGER_WAITING | string | Yes | Yes | Whether the device waits for the debugger when starting an application to debug.
**1**: The device waits for the debugger.
**0**: The device does not wait for the debugger. In this case, the application runs normally.| +| DEBUG_APP_PACKAGE | string | Yes | Yes | Bundle name of the application to be debugged. | +| ACCESSIBILITY_STATUS | string | Yes | Yes | Whether accessibility is enabled.
**1**: Accessibility is enabled.
**0**: Accessibility is disabled.| +| ACTIVATED_ACCESSIBILITY_SERVICES | string | Yes | Yes | List of activated accessibility features. | +| GEOLOCATION_ORIGINS_ALLOWED | string | Yes | Yes | Default geographic location that can be used by the browser. Multiple geographic locations are separated by spaces. | +| SKIP_USE_HINTS | string | Yes | Yes | Whether the application should attempt to skip all introductory hints at the first startup. This feature is intended for temporary or experienced users.
**1**: The application attempts to skip all introductory hints at the first startup.
**0**: The application does not skip all introductory hints at the first startup.| +| TOUCH_EXPLORATION_STATUS | string | Yes | Yes | Whether touch exploration is enabled.
**1**: Touch exploration is enabled.
**0**: Touch exploration is disabled.| + +## input + +Provides data items for setting input methods. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| DEFAULT_INPUT_METHOD | string | Yes | Yes | Default input method and its ID. | +| ACTIVATED_INPUT_METHOD_SUB_MODE | string | Yes | Yes | Type and ID of the default input method keyboard. | +| ACTIVATED_INPUT_METHODS | string | Yes | Yes | List of activated input methods.
The list is a string that contains the IDs and keyboard types of activated input methods. The IDs are separated by colons (:), and keyboard types are separated by semicolons (;). An example format is **ima0:keyboardType0;keyboardType1;ima1:ima2:keyboardTypes0,** where **ima** indicates the ID of an input method, and **keyboardType** indicates the keyboard type.| +| SELECTOR_VISIBILITY_FOR_INPUT_METHOD | string | Yes | Yes | Whether the input method selector is visible.
**1**: The input method selector is visible.
**0**: The input method selector is invisible.| +| AUTO_CAPS_TEXT_INPUT | string | Yes | Yes | Whether automatic capitalization is enabled for the text editor.
**0**: Automatic capitalization is disabled.
**1**: Automatic capitalization is enabled.| +| AUTO_PUNCTUATE_TEXT_INPUT | string | Yes | Yes | Whether automatic punctuation is enabled for the text editor. Automatic punctuation enables the text editor to convert two spaces into a period (.) and a space.
**0**: Automatic punctuation is disabled.
**1**: Automatic punctuation is enabled.| +| AUTO_REPLACE_TEXT_INPUT | string | Yes | Yes | Whether autocorrect is enabled for the text editor. Autocorrect enables the text editor to correct typos.
**0**: Autocorrect is disabled.
**1**: Autocorrect is enabled | +| SHOW_PASSWORD_TEXT_INPUT | string | Yes | Yes | Whether password presentation is enabled in the text editor. Password presentation enables the text editor to show password characters when the user types them.
**0**: Password presentation is disabled.
**1**: Password presentation is enabled.| + +## network + +Provides data items for setting network information. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| DATA_ROAMING_STATUS | string | Yes | Yes | Whether data roaming is enabled.
**true**: Data roaming is enabled.
**false**: Data roaming is disabled.| +| HTTP_PROXY_CFG | string | Yes | Yes | Host name and port number of the global HTTP proxy. The host name and port number are separated by a colon (:).| +| NETWORK_PREFERENCE_USAGE | string | Yes | Yes | User preferences for the network to use. | + +## phone + +Provides data items for setting the modes of answering incoming and outgoing calls. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| ------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| RTT_CALLING_STATUS | string | Yes | Yes | Whether the real-time text (RTT) feature is enabled. If this feature is enabled, incoming and outgoing calls are answered as RTT calls when supported by the device and carrier.
**1**: RTT is enabled.
**0**: RTT is disabled.| + +## sound + +Provides data items for setting the sound effects. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| ---------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| VIBRATE_WHILE_RINGING | string | Yes | Yes | Whether the device vibrates when it is ringing for an incoming call. This attribute is applicable to the phone and settings applications and affects only the scenario where the device rings for an incoming call. It does not affect any other application or scenario.| +| DEFAULT_ALARM_ALERT | string | Yes | Yes | Storage area of the system default alarms and alerts. | +| DTMF_TONE_TYPE_WHILE_DIALING | string | Yes | Yes | Type of the dual tone multi-frequency (DTMF) tone played while dialing.
**0**: normal short tone.
**1**: long tone.| +| DTMF_TONE_WHILE_DIALING | string | Yes | Yes | Whether the DTMF tone is played when dialing.
**1**: DTMF tone is played when dialing.
**0**: DTMF tone is not played when dialing.| +| AFFECTED_MODE_RINGER_STREAMS | string | Yes | Yes | Which audio streams are affected by changes on the ringing mode and Do Not Disturb (DND) mode. If you want a specific audio stream to be affected by changes of the ringing mode and DDN mode, set the corresponding bit to **1**.| +| AFFECTED_MUTE_STREAMS | string | Yes | Yes | Audio streams affected by the mute mode. If you want a specific audio stream to remain muted in mute mode, set the corresponding bit to **1**.| +| DEFAULT_NOTIFICATION_SOUND | string | Yes | Yes | Storage area of the system default notification tone. | +| DEFAULT_RINGTONE | string | Yes | Yes | Storage area of the system default ringtone. | +| SOUND_EFFECTS_STATUS | string | Yes | Yes | Whether the sound feature is available.
**0**: The feature is not available.
**1**: The feature is available. | +| VIBRATE_STATUS | string | Yes | Yes | Whether the device vibrates for an event. This attribute is used inside the system.
**1**: The device vibrates for an event.
**0**: The device does not vibrate for an event.| +| HAPTIC_FEEDBACK_STATUS | string | Yes | Yes | Whether haptic feedback is enabled.
**true**: Haptic feedback is enabled.
**false**: Haptic feedback is disabled.| + +## TTS + +Provides data items for setting text-to-speech (TTS) information. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core + +| Name | Type | Readable| Writable| Description | +| ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| DEFAULT_TTS_PITCH | string | Yes | Yes | Default pitch of the TTS engine.
100 = 1x. If the value is set to **200**, the frequency is twice the normal sound frequency.| +| DEFAULT_TTS_RATE | string | Yes | Yes | Default voice rate of the TTS engine.
100 = 1x. | +| DEFAULT_TTS_SYNTH | string | Yes | Yes | Default TTS engine. | +| ENABLED_TTS_PLUGINS | string | Yes | Yes | List of activated plug-in packages used for TTS. Multiple plug-in packages are separated by spaces. | + + +## wireless + +Provides data items for setting wireless network information. + +### Attributes + +**System capability**: SystemCapability.Applications.settings.Core +| Name | Type | Readable| Writable| Description | +| --------------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| BLUETOOTH_DISCOVER_ABILITY_STATUS | string | Yes | Yes | Whether the device can be discovered or connected by other devices through Bluetooth.
**0**: The device cannot be discovered or connected.
**1**: The device can be connected but cannot be discovered.
**2**: The device can be discovered and connected.| +| BLUETOOTH_DISCOVER_TIMEOUT | string | Yes | Yes | Duration for discovering a device through Bluetooth, in seconds.
After the duration expires, the device cannot be discovered through Bluetooth.| +| AIRPLANE_MODE_RADIOS | string | Yes | Yes | List of radio signals to be disabled when airplane mode is enabled.
Multiple radio signals are separated by commas (,). The list can include the following: **BLUETOOTH_RADIO**, **CELL_RADIO**, **NFC_RADIO**, and **WIFI_RADIO**.| +| BLUETOOTH_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that Bluetooth is disabled in airplane mode.| +| CELL_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that cellular radio is disabled in airplane mode.| +| NFC_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that NFC is disabled in airplane mode.| +| WIFI_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that Wi-Fi is disabled in airplane mode.| +| BLUETOOTH_STATUS | string | Yes | Yes | Whether Bluetooth is available.
**true**: Bluetooth is available.
**false**: Bluetooth is unavailable.| +| OWNER_LOCKDOWN_WIFI_CFG | string | Yes | Yes | Whether the Wi-Fi configuration created by the application of the device owner should be locked down.
**true**: The Wi-Fi configuration should be locked down.
**false**: The Wi-Fi configuration should not be locked down.| +| WIFI_DHCP_MAX_RETRY_COUNT | string | Yes | Yes | Maximum number of attempts to obtain an IP address from the DHCP server. | +| WIFI_TO_MOBILE_DATA_AWAKE_TIMEOUT | string | Yes | Yes | Maximum duration to hold a wake lock when waiting for the mobile data connection to establish after the Wi-Fi connection is disconnected. | +| WIFI_STATUS | string | Yes | Yes | Whether Wi-Fi is available.
**true**: Wi-Fi is available.
**false**: Wi-Fi is unavailable.| +| WIFI_WATCHDOG_STATUS | string | Yes | Yes | Whether Wi-Fi watchdog is available.
**true**: Wi-Fi watchdog is available.
**false**: Wi-Fi watchdog is unavailable.| -## settings.getUriSync +## setting.getURI + +getURI(name: string, callback: AsyncCallback\): void + +Obtains the URI of a data item. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| callback | AsyncCallback\ | Yes | Callback used to obtain the URI of the data item. | + +**Example** + +```js +settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS, (uri) => { + console.log(`callback:uri -> ${JSON.stringify(uri)}`) +}) +``` + +## setting.getURI + +getURI(name: string): Promise\ + +Obtains the URI of a data item. This API uses a promise to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------ | +| Promise\ | Promise used to return the URI of the data item.| + +**Example** + +```js +settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS).then((uri) => { + console.log(`promise:uri -> ${JSON.stringify(uri)}`) +}) +``` + +## setting.getValue + +getValue(dataAbilityHelper: DataAbilityHelper, name: string, callback: AsyncCallback\): void + +Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, value) => { + if (err) { + console.error(`Failed to get the setting. ${err.message} `); + return; + } + console.log(`callback:value -> ${JSON.stringify(value)}`) +}); +``` + +## setting.getValue + +getValue(dataAbilityHelper: DataAbilityHelper, name: string): Promise\ + +Obtains the value of a data item in the database. This API uses a promise to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------- | +| Promise\ | Promise used to return the value of the data item.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value) => { + console.log(`promise:value -> ${JSON.stringify(value)}`) +}); +``` + +## settings.setValue + +setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object, callback: AsyncCallback\): void + +Sets the value for a data item. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | object | Yes | Value of the data item. The value range varies by service. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the operation is successful; returns **false** otherwise. | + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update the value of the data item.) +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => { + console.log('Callback return whether value is set.'); +}); +``` + +## settings.setValue + +setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object): Promise\ + +Sets the value for a data item. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | object | Yes | Value of the data item. The value range varies by service. | + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------------------------- | +| Promise\ | Promise used to return the result. Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update the value of the data item.) +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => { + console.log('Callback return whether value is set.'); +}); +``` + +## settings.enableAirplaneMode + +enableAirplaneMode(enable: boolean, callback: AsyncCallback\): void + +Enables or disables airplane mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ----------------------------------------------- | +| enable | boolean | Yes | Whether airplane mode is enabled. **true** means that airplane mode is enabled, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let isEnabled = true; +settings.enableAirplaneMode(isEnabled, (err) => { + if (err) { + console.log('Failed to enable AirplaneMode.'); + return; + } + console.log('Return true if enable.'); +}) +``` + +## settings.enableAirplaneMode + +enableAirplaneMode(enable: boolean): Promise\ + +Enables or disables airplane mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------------------- | +| enable | boolean | Yes | Whether airplane mode is enabled. **true** means that airplane mode is enabled, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +let isEnabled = true; +settings.enableAirplaneMode(isEnabled).then(() => { + console.log('Succeeded in enabling AirplaneMode.'); +}).catch((err) => { + console.log(`Failed to enable AirplaneMode. Cause: ${err}`); +}) +``` + +## settings.canShowFloating + +canShowFloating(callback: AsyncCallback\): void + +Checks whether the application can be displayed in a floating window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the application can be displayed in a floating window; returns **false** otherwise.| + +**Example** + +```js +settings.canShowFloating((status) => { + console.log('Checks whether a specified application can show as float window.'); +}); +``` + +## settings.canShowFloating + +canShowFloating(): Promise\ + +Checks whether the application can be displayed in a floating window. This API uses a promise to return the result. + +**System capability**: SystemCapability.Applications.settings.Core + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.
Returns **true** if the application can be displayed in a floating window; returns **false** otherwise.| + +**Example** + +```js +settings.canShowFloating().then((status) => { + console.log('Checks whether a specified application can show as float window.'); +}); +``` + +## settings.getUriSync8+ getUriSync(name: string): string @@ -25,92 +483,89 @@ Obtains the URI of a data item. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| settings.display.SCREEN_BRIGHTNESS_STATUS | string | Yes| Brightness of the target data item.| -| settings.date.TIME_FORMAT | string | Yes| Time format of the target data item. Data | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------- | | string | URI of the data item.| **Example** -```ts - // Obtain the URI of a data item. - let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +```js +// Obtain the URI of a data item. +let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); ``` - -## settings.getValueSync +## settings.getValueSync8+ getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: string): string -Obtains the value of a data item. +Obtains the value of a data item. Unlike **getValue**, this API returns the result synchronously. **System capability**: SystemCapability.Applications.settings.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| -| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: **settings.display.SCREEN_BRIGHTNESS_STATUS**
    • Time format: **settings.date.TIME_FORMAT**
  • Custom data items
| -| defValue | string | Yes| Default value This parameter is user-defined. If it is not found in the database, the default value is returned.| + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this attribute as needed.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ---------------- | | string | Value of the data item.| **Example** -```ts - import featureAbility from '@ohos.ability.featureAbility'; +```js +import featureAbility from '@ohos.ability.featureAbility'; -// Obtain the value of settings.display.SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). +// Obtain the value of SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); let helper = featureAbility.acquireDataAbilityHelper(uri); let value = settings.getValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '10'); ``` - -## settings.setValueSync +## settings.setValueSync8+ setValueSync(dataAbilityHelper: DataAbilityHelper, name: string, value: string): boolean -Sets the value of a data item. +Sets the value for a data item. Unlike **setValue**, this API returns the result synchronously. If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database. -**Required permissions**: ohos.permission.MODIFY_SETTINGS +**Required permissions**: ohos.permission.MANAGE_SECUER_SETTINGS (available only to system applications) **System capability**: SystemCapability.Applications.settings.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| -| name | string | Yes| Name of the target data item. Data items can be classified as follows:
  • Existing data items in the database, for example:
    • Brightness: **settings.display.SCREEN_BRIGHTNESS_STATUS**
    • Time format: **settings.date.TIME_FORMAT**
  • Custom data items
| -| value | string | Yes| Value of the data item.The value of range with the service.| +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | string | Yes | Value of the data item. The value range varies by service. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | ------------------------------------------------------------ | | boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| **Example** -```ts - import featureAbility from '@ohos.ability.featureAbility'; +```js +import featureAbility from '@ohos.ability.featureAbility'; -// Update the value of settings.display.SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync - method will update the value of the data item.) +// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync API will update the value of the data item.) let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); let helper = featureAbility.acquireDataAbilityHelper(uri); let ret = settings.setValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100'); -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index a2d761225c3169bd6d9f5a7603232d4050c0342b..6622b4b719e95f2c87af19653fbf8a89905239f2 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -589,7 +589,7 @@ Obtains the account information list of the active SIM card. This API uses an as **Example** ```js -sim.getActiveSimAccountInfoList(0, (err, data) => { +sim.getActiveSimAccountInfoList((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy **Example** ```js -const name='China Mobile'; +let name = 'China Mobile'; sim.setShowName(0, name, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -744,7 +744,7 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom **Example** ```js -const name='China Mobile'; +let name = 'China Mobile'; let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); @@ -1096,9 +1096,9 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy ```js let lockInfo = { - lockType = 1, + lockType: sim.LockType.PIN_LOCK, password = "1234", - state = 0 + state: sim.LockState.LOCK_OFF }; sim.setLockState(0, lockInfo, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -1135,9 +1135,9 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom ```js let lockInfo = { - lockType = 1, + lockType: sim.LockType.PIN_LOCK, password = "1234", - state = 0 + state: sim.LockState.LOCK_OFF }; let promise = sim.setLockState(0, lockInfo); promise.then(data => { @@ -2236,12 +2236,12 @@ Adds contact numbers for the SIM card in the specified slot. This API uses an as ```js let diallingNumbersInof = { - alphaTag = "alpha", - number = "138xxxxxxxx", - recordNumber = 123, - pin2 = "1234" + alphaTag: "alpha", + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; -sim.addIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { +sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2277,12 +2277,12 @@ Adds contact numbers for the SIM card in the specified slot. This API uses a pro ```js let diallingNumbersInof = { - alphaTag = "alpha", - number = "138xxxxxxxx", - recordNumber = 123, - pin2 = "1234" + alphaTag: "alpha", + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; -let promise = sim.addIccDiallingNumbers(0, 1, diallingNumbersInof); +let promise = sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { console.log(`addIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -2315,12 +2315,12 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a ```js let diallingNumbersInof = { - alphaTag = "alpha", - number = "138xxxxxxxx", - recordNumber = 123, - pin2 = "1234" + alphaTag: "alpha", + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; -sim.delIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { +sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2356,12 +2356,12 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a ```js let diallingNumbersInof = { - alphaTag = "alpha", - number = "138xxxxxxxx", - recordNumber = 123, - pin2 = "1234" + alphaTag: "alpha", + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; -let promise = sim.delIccDiallingNumbers(0, 1, diallingNumbersInof); +let promise = sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { console.log(`delIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -2394,12 +2394,12 @@ Updates contact numbers for the SIM card in the specified slot. This API uses an ```js let diallingNumbersInof = { - alphaTag = "alpha", - number = "138xxxxxxxx", - recordNumber = 123, - pin2 = "1234" + alphaTag: "alpha", + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; -sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { +sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2435,12 +2435,12 @@ Updates contact numbers for the SIM card in the specified slot. This API uses a ```js let diallingNumbersInof = { - alphaTag = "alpha", - number = "138xxxxxxxx", - recordNumber = 123, - pin2 = "1234" + alphaTag: "alpha", + number: "138xxxxxxxx", + recordNumber: 123, + pin2: "1234" }; -let promise = sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof); +let promise = sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { console.log(`updateIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -2602,7 +2602,7 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba ```js let persoLockInfo = { - lockType = 0, + lockType = sim.PersoLockType.PN_PIN_LOCK, password = "1234" }; sim.unlockSimLock(0, persoLockInfo, (err, data) => { @@ -2640,7 +2640,7 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th ```js let persoLockInfo = { - lockType = 0, + lockType = sim.PersoLockType.PN_PIN_LOCK, password = "1234" }; let promise = sim.unlockSimLock(0, persoLockInfo); @@ -2683,8 +2683,6 @@ getOpKey(slotId: number): Promise Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2716,8 +2714,6 @@ getOpName(slotId: number, callback: AsyncCallback): void Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2742,8 +2738,6 @@ getOpName(slotId: number): Promise Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 5443e18d1bd7e01ca1bbe74f62fdd9cce061e343..6920c9dbf3aea204efb78c292e949a7ec0e4a053 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -397,7 +397,7 @@ Splits an SMS message into multiple segments. This API uses an asynchronous call **Example** ```js -string content= "long message"; +let content = "long message"; sms.splitMessage(content, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -431,7 +431,7 @@ Splits an SMS message into multiple segments. This API uses a promise to return **Example** ```js -string content = "long message"; +let content = "long message"; let promise = sms.splitMessage(content); promise.then(data => { console.log(`splitMessage success, promise: data->${JSON.stringify(data)}`); @@ -463,10 +463,10 @@ Adds a SIM message. This API uses an asynchronous callback to return the result. ```js let simMessageOptions = { - slotId = 0, - smsc = "test", - pdu = "xxxxxx", - status = 0 + slotId: 0, + smsc: "test", + pdu: "xxxxxx", + status: sms.SimMessageStatus.SIM_MESSAGE_STATUS_READ }; sms.addSimMessage(simMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -502,10 +502,10 @@ Adds a SIM message. This API uses a promise to return the result. ```js let simMessageOptions = { - slotId = 0, - smsc = "test", - pdu = "xxxxxx", - status = 0 + slotId: 0, + smsc: "test", + pdu: "xxxxxx", + status: sms.SimMessageStatus.SIM_MESSAGE_STATUS_READ }; let promise = sms.addSimMessage(simMessageOptions); promise.then(data => { @@ -607,9 +607,9 @@ Updates a SIM message. This API uses an asynchronous callback to return the resu ```js let updateSimMessageOptions = { - slotId = 0, - msgIndex = 1, - newStatus = 0, + slotId: 0, + msgIndex: 1, + newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, pdu = "xxxxxxx", smsc = "test" }; @@ -647,9 +647,9 @@ Updates a SIM message. This API uses a promise to return the result. ```js let updateSimMessageOptions = { - slotId = 0, - msgIndex = 1, - newStatus = 0, + slotId: 0, + msgIndex: 1, + newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, pdu = "xxxxxxx", smsc = "test" }; @@ -749,10 +749,11 @@ Sets the cell broadcast configuration. This API uses an asynchronous callback to ```js let cbConfigOptions = { - slotId = 0, - smsc = "test", - pdu = "xxxxxxxx", - status = 0 + slotId: 0, + enable: true, + startMessageId: 100, + endMessageId: 200, + ranType: sms.RanType.TYPE_GSM }; sms.setCBConfig(cbConfigOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -788,13 +789,14 @@ Sets the cell broadcast configuration. This API uses a promise to return the res ```js let cbConfigOptions = { - slotId = 0, - smsc = "test", - pdu = "xxxxxxxx", - status = 0 + slotId: 0, + enable: true, + startMessageId: 100, + endMessageId: 200, + ranType: sms.RanType.TYPE_GSM }; let promise = sms.setCBConfig(cbConfigOptions); -promise.then(data => +promise.then(data => { console.log(`setCBConfig success, promise: data->${JSON.stringify(data)}`); }).catch(err => { console.error(`setCBConfig failed, promise: err->${JSON.stringify(err)}`); @@ -859,7 +861,7 @@ Obtains SMS message segment information. This API uses a promise to return the r ```js let slotId = 0; let promise = sms.getSmsSegmentsInfo(slotId, "message", false); -promise.then(data => +promise.then(data => { console.log(`getSmsSegmentsInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { console.error(`getSmsSegmentsInfo failed, promise: err->${JSON.stringify(err)}`); @@ -886,7 +888,7 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t ```js sms.isImsSmsSupported((err, data) => { - console.log(`callback: err->${JSON.(err)}, data->${JSON.stringify(data)}`); + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1023,7 +1025,7 @@ Decodes MMS messages. This API uses a promise to return the result. ```js let mmsFilePathName = "filename"; -let promise = sms.getSmscAddr(mmsFilePathName); +let promise = sms.decodeMms(mmsFilePathName); promise.then(data => { console.log(`decodeMms success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1092,13 +1094,13 @@ Encodes MMS messages. This API uses a promise to return the result. ```js let mmsAcknowledgeInd = { - transactionId = "100", - version = 0x10, - reportAllowed = 128 + transactionId: "100", + version: sms.MmsVersionType.MMS_VERSION_1_0, + reportAllowed = sms.ReportType.MMS_YES }; let mmsInformation = { - messageType = 133, - mmsType = mmsAcknowledgeInd + messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, + mmsType: mmsAcknowledgeInd }; let promise = sms.encodeMms(mmsInformation); promise.then(data => { diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 77dd0bc0560d11837a5cfbb68f38fd3f39075310..cd0995948cc8354d05845c7156abcdfdfb558bda 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -316,7 +316,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { return; } console.log('bind success'); - let promise = udp.getState({}); + let promise = udp.getState(); promise.then(data => { console.log('getState success:' + JSON.stringify(data)); }).catch(err => { @@ -626,7 +626,7 @@ Defines the parameters for sending data over the UDPSocket connection. | Name | Type | Mandatory| Description | | ------- | ---------------------------------- | ---- | -------------- | -| data | string | Yes | Data to send. | +| data | string \| ArrayBuffer7+ | Yes | Data to send. | | address | [NetAddress](#netaddress) | Yes | Destination address.| ## UDPExtraOptions @@ -1434,7 +1434,7 @@ Defines the parameters for sending data over the TCPSocket connection. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| data | string | Yes | Data to send. | +| data | string\| ArrayBuffer7+ | Yes | Data to send. | | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| ## TCPExtraOptions diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 658082d2690c0ab00d76959a1a7ce1c97574ce5d..d646fd424d8f7fa6c431a388879e9cf63678a632 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -52,7 +52,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getTotalSizeOfVolume -getTotalSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void +getTotalSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): void Asynchronously obtains the total size of the specified volume. This API uses a callback to return the result. @@ -69,7 +69,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| + | callback | callback: AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| **Example** @@ -121,7 +121,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getFreeSizeOfVolume -getFreeSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void +getFreeSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): void Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. @@ -138,7 +138,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | ---------------------------- | | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| + | callback | callback: AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| **Example** @@ -206,7 +206,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | packageName | string | Yes | Bundle name of the application.| - | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| + | callback | callback: AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| **Example** @@ -251,7 +251,7 @@ Asynchronously obtains space information of the current third-party application. | Name | Type | Mandatory | Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | + | callback | callback: AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | **Example** @@ -323,7 +323,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory | Description | | -------- | ------------------------------------ | ---- | ------------------------ | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| + | callback | callback: AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| **Example** @@ -381,7 +381,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| + | callback | callback: AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| **Example** @@ -424,7 +424,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getSystemSize9+ -getSystemSize(callback:AsyncCallback<number>):void +getSystemSize(callback: AsyncCallback<number>): void Asynchronously obtains the system space. This API uses a callback to return the result. @@ -440,7 +440,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| + | callback | callback: AsyncCallback<number> | Yes | Callback used to return the system space obtained.| **Example** @@ -475,7 +475,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | --------------------- | ---------------- | - | Promise<[StorageStats](#StorageStats)> | Promise used to return the information obtained.| + | Promise<[StorageStats](#storagestats)> | Promise used to return the information obtained.| **Example** @@ -490,7 +490,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getUserStorageStats9+ -getUserStorageStats(userId: number, callback:AsyncCallback<StorageStats>):void +getUserStorageStats(userId: number, callback: AsyncCallback<StorageStats>): void Asynchronously obtains the space occupied by each type of user data. This API uses a callback to return the result. @@ -507,7 +507,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | - | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| + | callback | callback: AsyncCallback<[StorageStats](#storagestats)> | Yes | Callback invoked to return the information obtained.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index 82be7501dfcef800ba7bd6db6fc9e3759ac05bfa..6812d87828d55851d375eadba9dab6b2de55560a 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -9,13 +9,57 @@ ```js -import cipher from '@system.cipher' +import cipher from '@system.cipher'; ``` +## CipherResponse + +Defines the response to the cipher interface called. + +**System capability**: SystemCapability.Security.Cipher + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| text | string | Yes | Response content.| + +## CipherRsaOptions + +Defines the input parameters of **cipher.rsa()**. + +**System capability**: SystemCapability.Security.Cipher + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.| +| text | string | Yes | Text 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 to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes | RSA key. It is a public key in encryption and a private key in decryption. | +| transformation | string | No | RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| +| success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. | +| fail | (data: string, code: number) => void | No | Called when data fails to be encrypted or decrypted. | +| complete | () => void | No | Called when the execution is complete. | + +## CipherAesOptions + +Defines the input parameters of **cipher.aes()**. + +**System capability**: SystemCapability.Security.Cipher + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.| +| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes | Key used for encryption or decryption. It is a Base64 encoded string.| +| transformation | string | No | Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**. | +| iv | string | No | Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| +| ivOffset | string | No | Offset of the IV for AES-based encryption and decryption. The default value is **0**, which is the only value supported. | +| ivLen | string | No | Length of the IV, in bytes. This field is reserved. The default value is **16**, which is the only value supported.| +| success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. | +| fail | (data: string, code: number) => void | No | Called when data fails to be encrypted or decrypted. | +| complete | () => void | No | Called when the execution is complete. | ## cipher.rsa -rsa(Object): void +rsa(options: CipherRsaOptions): void Encrypts or decrypts data using RSA. @@ -25,13 +69,7 @@ Encrypts or decrypts data using RSA. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt | -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| -| key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| -| transformation | string | No| RSA 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.| +| options | [CipherRsaOptions](#cipherrsaoptions) | Yes| Parameters set for RSA encryption or decryption.| **Example** @@ -53,7 +91,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); @@ -86,7 +124,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); @@ -99,7 +137,7 @@ export default { ## cipher.aes -aes(Object): void +aes(options: CipherAesOptions): void Encrypts or decrypts data using AES. @@ -109,16 +147,7 @@ Encrypts or decrypts data using AES. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt | -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| -| key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| -| transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| -| iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| -| ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**, which is the only value supported.| -| ivLen | string | No| Length of the IV, in bytes. This field is reserved. The default value is **16**, which is the only value supported.| -| 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.| +| options | [CipherAesOptions](#cipheraesoptions) | Yes| Parameters set for AES encryption or decryption.| **Example** @@ -139,7 +168,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); @@ -159,7 +188,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to decrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.aes encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); diff --git a/en/application-dev/reference/apis/js-apis-system-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index daa6d4aac0d3ea39560a13de07b37c51c8b9226a..0a46cec929810e8f485a66b26445f1e3042b7672 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -1,6 +1,7 @@ # Notification -> ![icon-note.gif]public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.notification`](js-apis-notification.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -51,18 +52,17 @@ Displays a notification. **Example** ```javascript -export default { - show() { - notification.show({ - contentTitle: 'title info', - contentText: 'text', - clickAction: { - bundleName: 'com.example.testapp', - abilityName: 'notificationDemo', - uri: '/path/to/notification', - }, - }); - }, +export default { + show() { + notification.show({ + contentTitle: 'title info', + contentText: 'text', + clickAction: { + bundleName: 'com.example.testapp', + abilityName: 'notificationDemo', + uri: '/path/to/notification', + }, + }); + }, } -; ``` diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index ec32f9279c250a823484d0894e5ce56c82386601..193e6a66e01abe1a23b94805038b0613b7640b13 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -3,8 +3,8 @@ The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. > **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. +> +> - 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 @@ -60,7 +60,7 @@ Sets the system time. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| time | number | Yes | Timestamp to set, in milliseconds. | +| time | number | Yes | Timestamp to set, in milliseconds.| **Return value** @@ -83,7 +83,7 @@ Sets the system time. This API uses a promise to return the result. ## systemTime.getCurrentTime8+ -getCurrentTime(isNano?: boolean, callback: AsyncCallback<number>): void +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. @@ -93,7 +93,7 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | | callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -109,6 +109,33 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal ``` +## systemTime.getCurrentTime8+ + +getCurrentTime(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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + + ```js + systemTime.getCurrentTime((error, data) => { + if (error) { + console.error(`failed to systemTime.getCurrentTime because ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.getCurrentTime success data : ` + JSON.stringify(data)); + }); + ``` + + ## systemTime.getCurrentTime8+ getCurrentTime(isNano?: boolean): Promise<number> @@ -121,7 +148,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** @@ -142,7 +169,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return ## systemTime.getRealActiveTime8+ -getRealActiveTime(isNano?: boolean, callback: AsyncCallback<number>): void +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. @@ -152,7 +179,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | | callback | AsyncCallback<number> | Yes | Callback used to return the time.| **Example** @@ -168,6 +195,33 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ``` +## systemTime.getRealActiveTime8+ + +getRealActiveTime(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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + + ```js + systemTime.getRealActiveTime((error, data) => { + if (error) { + console.error(`failed to systemTime.getRealActiveTimebecause ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data)); + }); + ``` + + ## systemTime.getRealActiveTime8+ getRealActiveTime(isNano?: boolean): Promise<number> @@ -180,7 +234,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** @@ -201,7 +255,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(isNano?: boolean, callback: AsyncCallback<number>): void +getRealTime(isNano: boolean, 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. @@ -211,7 +265,7 @@ Obtains the time elapsed since system start, including the deep sleep time. This | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | | callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -229,6 +283,32 @@ Obtains the time elapsed since system start, including the deep sleep time. This ## systemTime.getRealTime8+ +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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + + ```js + systemTime.getRealTime((error, data) => { + if (error) { + console.error(`failed to systemTime.getRealTime because ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.getRealTime success data: ` + JSON.stringify(data)); + }); + ``` + +## systemTime.getRealTime8+ + getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system start, including the deep sleep time. This API uses a promise to return the result. @@ -239,7 +319,7 @@ Obtains the time elapsed since system start, including the deep sleep time. This | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** @@ -278,7 +358,7 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Example** ```js - var data = new Date("October 13, 2020 11:13:00"); + var data = new Date(); systemTime.setDate(data,(error, data) => { if (error) { console.error('failed to systemTime.setDate because ' + JSON.stringify(error)); @@ -314,7 +394,7 @@ Sets the system date. This API uses a promise to return the result. **Example** ```js - var data = new Date("October 13, 2020 11:13:00"); + var data = new Date(); systemTime.setDate(data).then((value) => { console.log(`systemTime.setDate success data : ` + JSON.stringify(value)); }).catch((error) => { diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md index f952b38c3de656864d42ad8c2c42b108b0c53f3d..b7880eebd39edf24bec47aafaece182f6a1ef5c2 100644 --- a/en/application-dev/reference/apis/js-apis-system-timer.md +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -2,7 +2,7 @@ The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services. -> **NOTE**
+> **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. @@ -24,12 +24,9 @@ Creates a timer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | -| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | -| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------| ---- | --------------------------------------------------------------------------- | +| options | [TimerOptions](#timeroptions) | Yes | Timer options. | **Return value** @@ -68,12 +65,9 @@ Creates a timer. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | -| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | -| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------| ---- | --------------------------------------------------------------------------- | +| options | [TimerOptions](#timeroptions) | Yes | Timer options. | **Return value** @@ -112,7 +106,7 @@ Starts a timer. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| timer | number | Yes | ID of the timer. | | triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | @@ -125,8 +119,10 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 10000, (error, data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime, (error, data) => { if (error) { console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); return; @@ -136,7 +132,7 @@ export default { } } ``` - + ## systemTime.startTimer startTimer(timer: number, triggerTime: number): Promise<void> @@ -149,9 +145,7 @@ Starts a timer. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | -| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | - +| timer | number | Yes | ID of the timer. | | triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | **Example** @@ -162,8 +156,10 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 10000).then((data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime).then((data) => { console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); }).catch((error) => { console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); @@ -196,9 +192,11 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) - systemTimer.stoptTimer(timerId, 10000, (error, data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) + systemTimer.stoptTimer(timerId, (error, data) => { if (error) { console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); return; @@ -222,7 +220,7 @@ Stops a timer. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| timer | number | Yes | ID of the timer. | **Example** @@ -233,9 +231,11 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) - systemTimer.stoptTimer(timerId, 10000).then((data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) + systemTimer.stoptTimer(timerId).then((data) => { console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); }).catch((error) => { console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); @@ -268,8 +268,10 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) systemTimer.destroyTimer(timerId, (error, data) => { if (error) { @@ -306,10 +308,12 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) - systemTimer.destroytTimer(timerId, 10000).then((data) => { + systemTimer.destroyTimer(timerId, 10000).then((data) => { console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); }).catch((error) => { console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); @@ -317,3 +321,17 @@ export default { } } ``` + + ## TimerOptions + +Defines the initialization options for **createTimer**. + +**System capability**: SystemCapability.MiscServices.Time + +| Name | Type | Mandatory| Description | +| -------- | ------------------| ---- | ------------------------------------------------------------------------------------------------------------------------- | +| type | number | Yes | **const TIMER_TYPE_REALTIME**: sets the timer to the CPU time type. (When the set time is later than the timer startup time, the timer expires.) If it is not specified, the timer is of the wall-time type.
**const TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**const TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**const TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported). | +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | +| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.) | +| callback | number | Yes | Callback used to return the timer ID. | diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index 7d8018a4e82916df0c218a10ca7d5e8fdb9e6364..f3a29a9cc683fecc38b4c935af7607bd2a5415b8 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -63,6 +63,29 @@ promise.then((data) => { }); ``` +## data.getDefaultCellularDataSlotIdSync + +getDefaultCellularDataSlotIdSync(): number + +Obtains the default SIM card used for mobile data synchronously. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| ------ | -------------------------------------------------- | +| number | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Example** + +```js +console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) +``` + + ## data.setDefaultCellularDataSlotId setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-tlsSocket.md b/en/application-dev/reference/apis/js-apis-tlsSocket.md new file mode 100644 index 0000000000000000000000000000000000000000..d734a1c4bbc6ec59e76bb2fbf47afcedf83ab30d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-tlsSocket.md @@ -0,0 +1,486 @@ +# TLSSocket + +The Transport Layer Security (TLS) protocol is designed to help protect the privacy of information at the transport layer. TLSSocket is an extension to socket communication. It provides higher security than socket communication by adding a security protection layer, which consists of the following submodules: key, certificate, and communication. + +> **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. + +## Modules to Import + +```js +import socket from '@ohos.net.tlssocket' +``` + +## socket.constructTLSSocketInstance + +constructTLSSocketInstance(): TLSSocket + +Creates a **TLSSocket** object. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Example** + +```js +let tlssocket = socket.constructTLSSocketInstance(); +``` + +## tlssocket.connect + +connect(options: TLSConnectOptions, callback: AsyncCallback\): void + +Sets up a TLSSocket connection, and creates and initializes a TLS session. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ---------------------------------------| ----| --------------- | +| options | [TLSConnectOptions](#tlsconnectoptions) | Yes | Parameters required for the connection.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Example** + +```js +let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: "xxx", + port: "xxxx", + family: 1, + }, + secureOptions: { + key: "xxxx", + cert: "xxxx", + ca: ["xxxx"], + passwd: "xxxx", + protocols: "TlsV1_2", + useRemoteCipherPrefer: true, + signatureAlgorithms: SHA256, + cipherSuites: AES256-SHA256, + }, +}; + +tlssocket.connect(options, (err, data) => { + console.info(err); + console.info(data); +}); +``` + +## tlssocket.connect + +connect(options: TLSConnectOptions): Promise\; + +Sets up a TLSSocket connection, and creates and initializes a TLS session. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | --------------------------------------| ----| --------------- | +| options | [TLSConnectOptions](#tlsconnectoptions) | Yes | Parameters required for the connection.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Example** + +```js +let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: "xxxx", + port: "xxxx", + family: 1, + }, + secureOptions: { + key: "xxxx", + cert: "xxxx", + ca: ["xxxx"], + passwd: "xxxx", + protocols: "TlsV1_2", + useRemoteCipherPrefer: true, + signatureAlgorithms: SHA256, + cipherSuites: AES256-SHA256, + }, +}; + +tlssocket.connect(options).then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getCertificate + +getCertificate(callback: AsyncCallback\): void; + +Obtains the local digital certificate after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +tlssocket.getCertificate((err, data) => { + if (err) { + console.log("getCertificate callback error = " + err); + } else { + console.log("getCertificate callback = " + data); + } +}); +``` + +## tlssocket.getCertificate + +getCertificate():Promise\; + +Obtains the local digital certificate after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.getCertificate().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getRemoteCertificate + +getRemoteCertificate(callback: AsyncCallback\): void; + +Obtains the remote digital certificate after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +tlssocket.getRemoteCertificate((err, data) => { + if (err) { + console.log("getRemoteCertificate callback error = " + err); + } else { + console.log("getRemoteCertificate callback = " + data); + } +}); +``` + +## tlssocket.getRemoteCertificate + +getRemoteCertificate():Promise\; + +Obtains the remote digital certificate after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.getRemoteCertificate().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getProtocol + +getProtocol(callback: AsyncCallback\): void; + +Obtains the communication protocol after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.getProtocol((err, data) => { + if (err) { + console.log("getProtocol callback error = " + err); + } else { + console.log("getProtocol callback = " + data); + } +}); +``` + +## tlssocket.getProtocol + +getProtocol():Promise\; + +Obtains the communication protocol after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.getProtocol().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getCipherSuites + +getCipherSuites(callback: AsyncCallback\>): void; + +Obtains the cipher suites supported by both parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.getCipherSuites((err, data) => { + if (err) { + console.log("getCipherSuites callback error = " + err); + } else { + console.log("getCipherSuites callback = " + data); + } +}); +``` + +## tlssocket.getCipherSuites + +getCipherSuites(): Promise\>; + +Obtains the cipher suites supported by both parties after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +tlssocket.getCipherSuites().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.getSignatureAlgorithms + +getSignatureAlgorithms(callback: AsyncCallback\>): void; + +Obtains the signing algorithms supported by both parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------| ---- | ---------------| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.getSignatureAlgorithms((err, data) => { + if (err) { + console.log("getSignatureAlgorithms callback error = " + err); + } else { + console.log("getSignatureAlgorithms callback = " + data); + } +}); +``` + +## tlssocket.getSignatureAlgorithms + +getSignatureAlgorithms(): Promise\>; + +Obtains the signing algorithms supported by both parties after a TLSSocket connection is established. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ---------------------- | -------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +tlssocket.getSignatureAlgorithms().then(data => { + console.info(data); +}).catch(err => { + console.error(err); +}); +``` + +## tlssocket.close + +close(callback: AsyncCallback\): void; + +Closes a TLSSocket connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +tlssocket.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } +}); +``` + +## tlssocket.close + +close(): Promise\; + +Closes a TLSSocket connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +tlssocket.close().then(() => + console.log("close success"); +}).catch(err => { + console.error(err); +}); +``` + +## TLSConnectOptions + +Defines a TLSSocket connection. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Description | +| -------------- | ------------------------------------- | -------------- | +| address | [NetAddress](#netaddress) | Gateway address. | +| secureOptions | [TLSSecureOptions](#tlssecureoptions) | TLS security options.| +| ALPNProtocols | Array\ | Application Layer Protocol Negotiation (ALPN) protocols. | + +## NetAddress + +Defines a network address. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Description | +| ------- | ------ | ---------------------------- | +| 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**. | + +## TLSSecureOptions + +Defines TLS security options. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Description | +| --------------------- | ---------------------- | ---------------------- | +| ca | string \| Array\ | CA certificate. | +| cert | string | Local digital certificate. | +| key | string | Private key of the local digital certificate. | +| passwd | string | Password. | +| protocols | string | Protocols. | +| useRemoteCipherPrefer | boolean | Whether to use the remote cipher suite preferentially.| +| signatureAlgorithms | string | Signing algorithms. | +| cipherSuites | string | Cipher suites. | diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 91013f97245cf0b63073b88c51af91705324038a..bcbac5414055dfb654ab1264ab04f92e629cb3f3 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -43,13 +43,13 @@ Obtains an **OnlineUpdater** object. ```ts try { - var upgradeInfo = { + const upgradeInfo = { upgradeApp: "com.ohos.ota.updateclient", businessType: { vendor: update.BusinessVendor.PUBLIC, subType: update.BusinessSubType.FIRMWARE } - } + }; let updater = update.getOnlineUpdater(upgradeInfo); } catch(error) { console.error(`Fail to get updater error: ${error}`); @@ -233,15 +233,15 @@ Obtains the description file of the new version. This API uses an asynchronous c ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => { console.log(`getNewVersionDescription info ${JSON.stringify(info)}`); @@ -276,15 +276,15 @@ Obtains the description file of the new version. This API uses a promise to retu ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => { console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); @@ -368,10 +368,10 @@ Obtains the description file of the current version. This API uses an asynchrono ```ts // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getCurrentVersionDescription(descriptionOptions, (err, info) => { console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`); @@ -405,10 +405,10 @@ Obtains the description file of the current version. This API uses a promise to ```ts // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getCurrentVersionDescription(descriptionOptions).then(info => { console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`); @@ -489,15 +489,15 @@ Downloads the new version. This API uses an asynchronous callback to return the ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Download options -var downloadOptions = { +const downloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network order: update.Order.DOWNLOAD // Download -} +}; updater.download(versionDigestInfo, downloadOptions, (err) => { console.log(`download error ${JSON.stringify(err)}`); }); @@ -530,15 +530,15 @@ Downloads the new version. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Download options -var downloadOptions = { +const downloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network order: update.Order.DOWNLOAD // Download -} +}; updater.download(versionDigestInfo, downloadOptions).then(() => { console.log(`download start`); }).catch(err => { @@ -568,14 +568,14 @@ Resumes download of the new version. This API uses an asynchronous callback to r ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for resuming download -var resumeDownloadOptions = { +const resumeDownloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network -} +}; updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => { console.log(`resumeDownload error ${JSON.stringify(err)}`); }); @@ -608,14 +608,14 @@ Resumes download of the new version. This API uses a promise to return the resul ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for resuming download -var resumeDownloadOptions = { +const resumeDownloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network -} +}; updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => { console.log(`resumeDownload start`); }).catch(err => { @@ -645,14 +645,14 @@ Pauses download of the new version. This API uses an asynchronous callback to re ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for pausing download -var pauseDownloadOptions = { +const pauseDownloadOptions = { isAllowAutoResume: true // Whether to allow automatic resuming of download -} +}; updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => { console.log(`pauseDownload error ${JSON.stringify(err)}`); }); @@ -685,14 +685,14 @@ Resumes download of the new version. This API uses a promise to return the resul ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for pausing download -var pauseDownloadOptions = { +const pauseDownloadOptions = { isAllowAutoResume: true // Whether to allow automatic resuming of download -} +}; updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => { console.log(`pauseDownload`); }).catch(err => { @@ -722,14 +722,14 @@ Updates the version. This API uses an asynchronous callback to return the result ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Installation options -var upgradeOptions = { +const upgradeOptions = { order: update.Order.INSTALL // Installation command -} +}; updater.upgrade(versionDigestInfo, upgradeOptions, (err) => { console.log(`upgrade error ${JSON.stringify(err)}`); }); @@ -762,14 +762,14 @@ Updates the version. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Installation options -var upgradeOptions = { +const upgradeOptions = { order: update.Order.INSTALL // Installation command -} +}; updater.upgrade(versionDigestInfo, upgradeOptions).then(() => { console.log(`upgrade start`); }).catch(err => { @@ -799,14 +799,14 @@ Clears errors. This API uses an asynchronous callback to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for clearing errors -var clearOptions = { +const clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, -} +}; updater.clearError(versionDigestInfo, clearOptions, (err) => { console.log(`clearError error ${JSON.stringify(err)}`); }); @@ -839,14 +839,14 @@ Clears errors. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for clearing errors -var clearOptions = { +lconstet clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, -} +}; updater.clearError(versionDigestInfo, clearOptions).then(() => { console.log(`clearError success`); }).catch(err => { @@ -926,7 +926,7 @@ Sets the update policy. This API uses an asynchronous callback to return the res **Example** ```ts -let policy = { +const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes @@ -961,7 +961,7 @@ Sets the update policy. This API uses a promise to return the result. **Example** ```ts -let policy = { +const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes @@ -1041,10 +1041,10 @@ Enables listening for update events. This API uses an asynchronous callback to r **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; updater.on(eventClassifyInfo, (eventInfo) => { console.log("updater on " + JSON.stringify(eventInfo)); @@ -1068,10 +1068,10 @@ Disables listening for update events. This API uses an asynchronous callback to **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; updater.off(eventClassifyInfo, (eventInfo) => { console.log("updater off " + JSON.stringify(eventInfo)); @@ -1153,10 +1153,10 @@ Verifies the update package. This API uses an asynchronous callback to return th **Example** ```ts -var upgradeFile = { +const upgradeFile = { fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -} +}; localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => { console.log(`factoryReset error ${JSON.stringify(err)}`); @@ -1189,10 +1189,10 @@ Verifies the update package. This API uses a promise to return the result. **Example** ```ts -var upgradeFile = { +const upgradeFile = { fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -} +}; localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => { console.log(`verifyUpgradePackage success`); }).catch(err => { @@ -1219,10 +1219,10 @@ Installs the update package. This API uses an asynchronous callback to return th **Example** ```ts -var upgradeFiles = [{ +const upgradeFiles = [{ fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -}] +}]; localUpdater.applyNewVersion(upgradeFiles, (err) => { console.log(`applyNewVersion error ${JSON.stringify(err)}`); @@ -1248,10 +1248,10 @@ Installs the update package. This API uses a promise to return the result. **Example** ```ts -var upgradeFiles = [{ +localUpdater upgradeFiles = [{ fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -}] +}]; localUpdater.applyNewVersion(upgradeFiles).then(() => { console.log(`applyNewVersion success`); }).catch(err => { @@ -1276,10 +1276,10 @@ Enables listening for update events. This API uses an asynchronous callback to r **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; function onTaskUpdate(eventInfo) { console.log(`on eventInfo id `, eventInfo.eventId); @@ -1305,10 +1305,10 @@ Disables listening for update events. This API uses an asynchronous callback to **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; function onTaskUpdate(eventInfo) { console.log(`on eventInfo id `, eventInfo.eventId); diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index c060118f7e466da51f2ee5b7fdd6ad20f7e256ca..221decfb35ae0a6667eb9f96c60c713f8536949b 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -128,7 +128,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th | Type| Description| | -------- | -------- | -| IterableIterator<[string, string]> | ES6 iterator.| +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -192,7 +192,7 @@ Obtains the value of the first key-value pair based on the specified key. | Type| Description| | -------- | -------- | | string | Returns the value of the first key-value pair if obtained.| -| null | Returns null if no value is obtained.| +| null | Returns **null** if no value is obtained.| **Example** @@ -333,7 +333,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th | Type| Description| | -------- | -------- | -| IterableIterator<[string, string]> | ES6 iterator.| +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -404,7 +404,7 @@ Creates a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| **Example** @@ -442,7 +442,7 @@ Converts the parsed URL into a string. ```js const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toString() +url.toString(); ``` @@ -463,5 +463,5 @@ Converts the parsed URL into a JSON string. **Example** ```js const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toJSON() +url.toJSON(); ``` diff --git a/en/application-dev/reference/apis/js-apis-userfilemanager.md b/en/application-dev/reference/apis/js-apis-userfilemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..77805c1c54764ae6c9fdc2498fbead88db696a84 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-userfilemanager.md @@ -0,0 +1,2520 @@ +# User Data Management + +> **NOTE**
+> This module is supported since API Version 9. Updates will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import userFileManager from '@ohos.filemanagement.userfile_manager'; +``` + +## userFileManager.getUserFileMgr + +getUserFileMgr(context: Context): UserFileManager + +Obtains a **UserFileManager** instance. This instance can be used to access and modify user media data (such as audio and video files, images, and documents). + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| context | [Context](#../apis/js-apis-Context.md) | Yes | Context of the ability instance.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| + +**Example** + +```ts +const context = getContext(this); +let userFileMgr = userfilemanager.getUserFileMgr(context); +``` + +## userFileManager.getUserFileMgr + +getUserFileMgr(): UserFileManager + +Obtains a **UserFileManager** instance.This instance can be used to access and modify user media data (such as audio and video clips, images, and documents). + +**Model restriction**: This API can be used only in the FA model. + +> **NOTE**
You are advised to use [UserFileManager.getUserFileMgr](#userfilemanagergetuserfilemgr), the API used in the stage model. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ----------------------------- | :--------- | +| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| + +**Example** + +```js +let userFileMgr = userfilemanager.getUserFileMgr(); +``` + +## UserFileManager + +### getPublicDirectory + +getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): void; + +Obtains the preset public directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [DirectoryType](#directorytype) | Yes | Type of the public directory. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the public directory.| + +**Example** + +```ts +async function getPublicDirectoryDemoCallback() { + console.info('getPublicDirectoryDemo'); + let DIR_CAMERA = directoryType.DIR_CAMERA; + console.info('DIR_CAMERA', DIR_CAMERA); + userFileMgr.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { + if (dicResult == 'Camera/') { + console.info('mediaLibraryTest : getPublicDirectory passed'); + } else { + console.info('mediaLibraryTest : getPublicDirectory failed'); + } + }); +} +``` + +### getPublicDirectory + +getPublicDirectory(type: DirectoryType): Promise<string>; + +Obtains the preset public directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------ | +| type | [DirectoryType](#directorytype) | Yes | Type of the public directory.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------- | +| Promise\ | Promise used to return the public directory.| + +**Example** + +```ts +async function getPublicDirectoryDemoPromise() { + console.info('getPublicDirectoryDemo'); + let DIR_CAMERA = directoryType.DIR_CAMERA; + try { + let dicResult = await userFileMgr.getPublicDirectory(DIR_CAMERA); + console.info('mediaLibraryTest : getPublicDirectory passed, result = ', dicResult); + } catch (err) { + console.info('mediaLibraryTest : getPublicDirectory failed, message = ', err); + } +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; + +Obtains file assets. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function getFileAssetsDemoCallback() { + console.info('getFileAssets'); + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE + let fetchOp = { + selections: '', + selectionArgs: [], + }; + + userFileMgr.getFileAssets([imageType, ], fetchOp, async (err, fetchFileResult) => { + if (fetchFileResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchFileResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + }; + } + }) +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; + +Obtains file assets. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ---------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media type to obtain.| +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| + +**Example** + +```ts +async function getFileAssetsDemoPromise() { + console.info('getFileAssets'); + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE + let fetchOp = { + selections: '', + selectionArgs: [], + }; + try { + var fetchFileResult = await userFileMgr.getFileAssets([imageType, ], fetchOp) + } catch (err) { + console.info('getFileAssets failed, message = ', err); + } + + if (fetchFileResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchFileResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + }; + } +} +``` + +### on + +on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void + +Subscribes to changes of the file management library. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Media type to subscribe to.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**fileChange** indicates the file change.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | Yes | Callback that returns no value. | + +**Example** + +```ts +async function onDemo() { + console.info('onDemo') + userFileMgr.on('imageChange', () => { + // Image file changes. Do something. + }); +} +``` + +### off + +off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void + +Unsubscribes from changes of the file management library. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Media type to unsubscribe from.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**fileChange** indicates the file change.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | No | Callback that returns no value. | + +**Example** + +```ts +async function offDemo() { + console.info('offDemo') + userFileMgr.off('imageChange', () => { + // stop listening success + }); +} +``` + +### createAsset + +createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void + +Creates a file asset. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------- | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype) | Yes | Media type. | +| displayName | string | Yes | File name to display. | +| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.| +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset created. | + +**Example** + +```ts +async function createAssetDemoCallback() { + console.info('createAssetDemo') + let mediaType = userfile_manager.MediaType.FILE; + let DIR_DOC = directoryType.DIR_DOCUMENTS; + const path = await userFileMgr.getPublicDirectory(DIR_DOC); + userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/', (err, fileAsset) => { + if (err == undefined) { + console.info('createAsset successfully'); + } else { + console.info('createAsset failed, message = ', err); + } + }) +} +``` + +### createAsset + +createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise<FileAsset>; + +Creates a file asset. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------- | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype) | Yes | Media type. | +| displayName | string | Yes | File name to display. | +| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset created.| + +**Example** + +```ts +async function createAssetDemoPromise() { + console.info('createAssetDemo') + let mediaType = userfile_manager.MediaType.FILE; + let DIR_DOC = directoryType.DIR_DOCUMENTS; + const path = await userFileMgr.getPublicDirectory(DIR_DOC); + try { + let fileAsset = await userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/') + console.info('createAsset successfully'); + } catch (err) { + console.info('createAsset failed, message = ', err); + } +} +``` + +### deleteAsset + +deleteAsset(uri: string, callback: AsyncCallback<void>): void; + +Deletes a file asset. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------- | +| uri | string | Yes | URI of the file to delete. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the result.| + +**Example** + +```ts +async function deleteAssetDemoCallback() { + console.info('deleteAssetDemo') + let fileKeyObj = userfile_manager.FileKey + let fileType = userfile_manager.MediaType.FILE + let option = { + selections: '', + selectionArgs: [], + }; + try { + const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); + var asset = await fetchFileResult.getFirstObject(); + } catch(err) { + console.info('fetch failed, message =', err) + } + + if (asset == undefined) { + console.error('asset not exist') + return + } + userFileMgr.deleteAsset(asset.uri, (err) => { + if (err == undefined) { + console.info("deleteAsset successfully"); + } else { + console.info("deleteAsset failed with error:"+ err); + } + }); +} +``` + +### deleteAsset + +deleteAsset(uri: string): Promise<void>; + +Deletes a file asset. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| uri | string | Yes | URI of the file to delete.| + +**Return value** + +| Type | Description | +| ---------------- | --------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```ts +async function deleteAssetDemoPromise() { + console.info('deleteAssetDemo') + let fileKeyObj = userfile_manager.FileKey + let fileType = userfile_manager.MediaType.FILE + let option = { + selections: '', + selectionArgs: [], + }; + try { + const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); + var asset = await fetchFileResult.getFirstObject(); + } catch(err) { + console.info('fetch failed, message =', err) + } + if (asset == undefined) { + console.error('asset not exist') + return + } + try { + await userFileMgr.deleteAsset(asset.uri); + console.info("deleteAsset successfully"); + } catch (err) { + console.info("deleteAsset failed with error:"+ err); + } +} +``` + +### getAlbums + +getAlbums(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. | +| callback | AsyncCallback<Array<[Album](#album)>> | Yes | Callback invoked to return the album list.| + +**Example** + +```ts +async function getAlbumsDemoCallback() { + console.info('getAlbumsDemo') + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp, (err, albumList) => { + if (albumList != undefined) { + const album = albumList[0]; + console.info('first album.albumName = ' + album.albumName); + console.info('album.count = ' + albumList.length); + } else { + console.info('getAlbum fail, message = ' + err); + } + }) +} +``` + +### getAlbums + +getAlbums(type: Array<MediaType>, options: MediaFetchOptions): Promise>; + +Obtains albums. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | -------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain.| +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. | + +**Return value** + +| Type | Description | +| ------------------------ | -------------------------- | +| Promise> | Promise used to return the album list.| + +**Example** + +```ts +async function getAlbumsDemoPromise() { + console.info('getAlbumsDemo') + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + try { + let albumList = await userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp); + const album = albumList[0]; + console.info('first album.albumName = ' + album.albumName); + console.info('album.count = ' + albumList.length); + } catch (err) { + console.info('getAlbum fail, message = ' + err); + } +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback): void + +Obtains the system album. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------- | +| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain. | +| callback | AsyncCallback> | Yes | Callback invoked to return the system album obtained.| + +**Example** + +```ts +async function getPrivateAlbumDemoCallback() { + console.info('getPrivateAlbumDemo') + userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH, async (err, albumArray) => { + if (err == undefined) { + console.info('getPrivateAlbum ok'); + try { + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); + } catch (err) { + console.info('getFileAssets failed. message = ', err); + } + // Get file count in trash album + let count = fetchResult.getCount(); + console.info('fetchResult count = ', count) + // Get fileAssets in trash album + let trashAsset = await fetchResult.getFirstObject(); + // Get file trashed date + let isTrash = trashAsset.isTrash(); + console.info('is trashed', isTrash) + } else { + console.info('getPrivateAlbum failed. message = ', err); + } + }); +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: VirtualAlbumType): Promise + +Obtains the system album. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------- | ---- | ------------ | +| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain.| + +**Return value** + +| Type | Description | +| ------------------------------- | --------------------------------- | +| Promise> | Promise used to return the system album obtained.| + +**Example** + +```ts +async function getPrivateAlbumDemoPromise() { + console.info('getPrivateAlbumDemo'); + try { + var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); + } catch(err) { + console.info('getPrivateAlbum failed. message = ', err); + } + try { + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); + } catch (err) { + console.info('getFileAssets failed. message = ', err); + } + // Get file count in trash album + let count = fetchResult.getCount(); + console.info('fetchResult count = ', count) + // Get fileAssets in trash album + let trashAsset = await fetchResult.getFirstObject(); + + // Get file trashed date + let isTrash = trashAsset.isTrash(); + console.info('is trashed', isTrash) +} +``` + +### getActivePeers + +getActivePeers(callback: AsyncCallback>): void; + +Obtains information about online peer devices. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| callback | AsyncCallback> | Yes | Callback invoked to return the online device list.| + +**Example** + +```ts +async function getActivePeersDemoCallback() { + console.info('getActivePeersDemo') + var devicesInfo = userFileMgr.getActivePeers((err, devicesInfo) => { + if (err == undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getActivePeers failed. message = ', err) + } + }); +} +``` + +### getActivePeers + +getActivePeers(): Promise>; + +Obtains information about online peer devices. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Return value** + +| Type | Description | +| --------------------------- | ----------------------------- | +| Promise> | Promise used to return the online device list.| + +**Example** + +```ts +async function getActivePeersDemoPromise() { + console.info('getActivePeersDemo') + try { + var devicesInfo = await userFileMgr.getActivePeers(); + } catch (err) { + console.info('getActivePeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail') + } +} +``` + +### getAllPeers + +getAllPeers(callback: AsyncCallback>): void; + +Obtains information about all peer devices. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| callback | AsyncCallback> | Yes | Callback invoked to return the peer device list.| + +**Example** + +```ts +async function getAllPeersDemoCallback() { + console.info('getAllPeersDemo') + var devicesInfo = await userFileMgr.getAllPeers((err, devicesInfo) => { + if (err == undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getAllPeers failed. message = ', err) + } + }); +} +``` + +### getAllPeers + +getAllPeers(): Promise>; + +Obtains information about all peer devices. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Return value** + +| Type | Description | +| --------------------------- | ----------------------------- | +| Promise> | Promise used to return the peer device list.| + +**Example** + +```ts +async function getAllPeersDemoPromise() { + console.info('getAllPeersDemo') + try { + var devicesInfo = await userFileMgr.getAllPeers(); + } catch (err) { + console.info('getAllPeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail') + } +} +``` + +### release + +release(callback: AsyncCallback<void>): void + +Releases this **UserFileManager** instance. This API uses an asynchronous callback to return the result. +Call this API when the APIs in the **UserFileManager** instance are no longer used. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```ts +async function releaseDemoCallback() { + console.info('releaseDemo'); + userFileMgr.release((err) => { + if (err != undefined) { + console.info('release failed. message = ', err); + } else { + console.info('release ok.'); + } + }) +} +``` + +### release + +release(): Promise<void> + +Releases this **UserFileManager** instance. This API uses a promise to return the result. +Call this API when the APIs in the **UserFileManager** instance are no longer used. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | --------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```ts +async function releaseDemoPromise() { + console.info('releaseDemo'); + try { + await userFileMgr.release(); + console.info('release ok.'); + } catch (err) { + console.info('release failed. message = ', err); + } +} +``` + +## FileAsset + +Provides APIs for encapsulating file asset attributes. + +### Attributes + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | +| uri | string | Yes | No | File asset URI, for example, **dataability:///media/image/2**. | +| mediaType | [MediaType](#mediatype) | Yes | No | Media type. | +| displayName | string | Yes | Yes | File name, including the file name extension, to display. | + + +### isDirectory + +isDirectory(callback: AsyncCallback<boolean>): void + +Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isDirectory((err, isDirectory) => { + // do something + }); +} +``` + +### isDirectory + +isDirectory():Promise<boolean> + +Checks whether this file asset is a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ---------------------- | ---------------------------- | +| Promise<boolean> | Promise used to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isDirectory().then(function(isDirectory){ + console.info("isDirectory result:"+ isDirectory); + }).catch(function(err){ + console.info("isDirectory failed with error:"+ err); + }); +} +``` + +### commitModify + +commitModify(callback: AsyncCallback<void>): void + +Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.title = 'newtitle'; + asset.commitModify(() => { + console.info('commitModify success'); + }); +} +``` + +### commitModify + +commitModify(): Promise<void> + +Commits the modification on the file metadata to the database. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.title = 'newtitle'; + asset.commitModify(); +} +``` + +### open + +open(mode: string, callback: AsyncCallback<number>): void + +Opens this file asset. This API uses an asynchronous callback to return the result. + +**NOTE**
Currently, the write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| +| callback | AsyncCallback<number> | Yes | Callback used to return the file handle. | + +**Example** + +```js +async function example() { + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); + const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); + asset.open('rw', (openError, fd) => { + if(fd > 0){ + asset.close(fd); + }else{ + console.info('File Open Failed!' + openError); + } + }); +} +``` + +### open + +open(mode: string): Promise<number> + +Opens this file asset. This API uses a promise to return the result. + +**NOTE**
Currently, the write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------------------- | +| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| + +**Return value** + +| Type | Description | +| --------------------- | ------------- | +| Promise<number> | Promise used to return the file handle.| + +**Example** + +```js +async function example() { + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); + const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); + asset.open('rw') + .then((fd) => { + console.info('File fd!' + fd); + }) + .catch((err) => { + console.info('File err!' + err); + }); +} +``` + +### close + +close(fd: number, callback: AsyncCallback<void>): void + +Closes this file asset. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| fd | number | Yes | File descriptor.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd, (closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); + }); +} +``` + +### close + +close(fd: number): Promise<void> + +Closes this file asset. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| fd | number | Yes | File descriptor.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd).then((closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); + }); +} +``` + +### getThumbnail + +getThumbnail(callback: AsyncCallback<image.PixelMap>): void + +Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------- | +| callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail((err, pixelmap) => { + console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }); +} +``` + +### getThumbnail + +getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void + +Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------- | +| size | [Size](#size) | Yes | Size of the thumbnail to obtain. | +| callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let size = { width: 720, height: 720 }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail(size, (err, pixelmap) => { + console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }); +} +``` + +### getThumbnail + +getThumbnail(size?: Size): Promise<image.PixelMap> + +Obtains the file thumbnail of the given size. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------- | ---- | ----- | +| size | [Size](#size) | No | Size of the thumbnail to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------- | --------------------- | +| Promise<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Promise used to return the pixel map of the thumbnail.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let size = { width: 720, height: 720 }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail(size) + .then((pixelmap) => { + console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }) + .catch((err) => { + console.info('mediaLibraryTest : getThumbnail fail'+ err); + }); +} +``` + +### favorite + +favorite(isFavorite: boolean, callback: AsyncCallback<void>): void + +Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ---------------------------------- | +| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.favorite(true,function(err){ + // Do something. + }); +} +``` + +### favorite + +favorite(isFavorite: boolean): Promise<void> + +Favorites or unfavorites this file asset. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ---------------------------------- | +| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.favorite(true).then(function() { + console.info("favorite successfully"); + }).catch(function(err){ + console.info("favorite failed with error:"+ err); + }); +} +``` + +### isFavorite + +isFavorite(callback: AsyncCallback<boolean>): void + +Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ----------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isFavorite((err, isFavorite) => { + if (isFavorite) { + console.info('FileAsset is favorite'); + }else{ + console.info('FileAsset is not favorite'); + } + }); +} +``` + +### isFavorite + +isFavorite():Promise<boolean> + +Checks whether this file asset is favorited. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ---------------------- | ------------------ | +| Promise<boolean> | Promise used to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isFavorite().then(function(isFavorite){ + console.info("isFavorite result:"+ isFavorite); + }).catch(function(err){ + console.info("isFavorite failed with error:"+ err); + }); +} +``` + +### trash + +trash(isTrash: boolean, callback: AsyncCallback<void>): void + +Moves this file asset to the trash. This API uses an asynchronous callback to return the result. + +Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------- | +| isTrash | boolean | Yes | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.trash(true, trashCallBack); + function trashCallBack(err, trash) { + console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash'); + } +} +``` + +### trash + +trash(isTrash: boolean): Promise<void> + +Moves this file asset to the trash. This API uses a promise to return the result. + +Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | --------- | +| isTrash | boolean | Yes | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.trash(true).then(function() { + console.info("trash successfully"); + }).catch(function(err){ + console.info("trash failed with error:"+ err); + }); +} +``` + +### isTrash + +isTrash(callback: AsyncCallback<boolean>): void + +Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | --------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isTrash((err, isTrash) => { + if (isTrash == undefined) { + console.error('Failed to get trash state: ' + err); + return; + } + console.info('Get trash state success: ' + isTrash); + }); +} +``` + +### isTrash + +isTrash():Promise<boolean> + +Checks whether this file asset is in the trash. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise used to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isTrash().then(function(isTrash){ + console.info("isTrash result: " + isTrash); + }).catch(function(err){ + console.error("isTrash failed with error: " + err); + }); +} +``` + +## FetchFileResult + +Provides APIs to manage the file retrieval result. + +### getCount + +getCount(): number + +Obtains the total number of files in the result set. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Total number of files.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; + let getFileCountOneOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getFileCountOneOp); + const fetchCount = fetchFileResult.getCount(); +} +``` + +### isAfterLast + +isAfterLast(): boolean + +Checks whether the cursor is in the last row of the result set. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------- | ---------------------------------- | +| boolean | Returns **true** if the cursor is in the last row of the result set; returns **false** otherwise.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const fetchCount = fetchFileResult.getCount(); + console.info('mediaLibraryTest : count:' + fetchCount); + let fileAsset = await fetchFileResult.getFirstObject(); + for (var i = 1; i < fetchCount; i++) { + fileAsset = await fetchFileResult.getNextObject(); + if(i == fetchCount - 1) { + console.info('mediaLibraryTest : isLast'); + var result = fetchFileResult.isAfterLast(); + console.info('mediaLibraryTest : isAfterLast:' + result); + console.info('mediaLibraryTest : isAfterLast end'); + fetchFileResult.close(); + } + } +} +``` + +### close + +close(): void + +Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.close(); +} +``` + +### getFirstObject + +getFirstObject(callback: AsyncCallback<FileAsset>): void + +Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the first file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getFirstObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getFirstObject + +getFirstObject(): Promise<FileAsset> + +Obtains the first file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the first file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getFirstObject().then(function(fileAsset){ + console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); + }).catch(function(err){ + console.info("getFirstObject failed with error:"+ err); + }); +} +``` + +### getNextObject + + getNextObject(callback: AsyncCallback<FileAsset>): void + +Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ----------------------------------------- | +| callbacke | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the next file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getNextObject + + getNextObject(): Promise<FileAsset> + +Obtains the next file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the next file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const fetchCount = fetchFileResult.getCount(); + console.info('mediaLibraryTest : count:' + fetchCount); + let fileAsset = await fetchFileResult.getNextObject(); +} +``` + +### getLastObject + +getLastObject(callback: AsyncCallback<FileAsset>): void + +Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | --------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the last file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getLastObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getLastObject + +getLastObject(): Promise<FileAsset> + +Obtains the last file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the last file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + let lastObject = await fetchFileResult.getLastObject(); +} +``` + +### getPositionObject + +getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void + +Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------ | +| index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset obtained.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getPositionObject(0, (err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getPositionObject + +getPositionObject(index: number): Promise<FileAsset> + +Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | -------------- | +| index | number | Yes | Index of the file asset to obtain. The value starts from **0**.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset obtained.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getPositionObject(1) .then(function (fileAsset){ + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }).catch(function (err) { + console.info("getFileAssets failed with error:" + err); + }); +} +``` + +## Album + +Provides APIs to manage albums. + +### Attributes + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable | Writable | Description | +| ------------ | ------ | ---- | ---- | ------- | +| albumName | string | Yes | Yes | Album name. | +| albumUri | string | Yes | No | Album URI. | +| dateModified | number | Yes | No | Date when the album was last 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. + +### commitModify + +commitModify(callback: AsyncCallback<void>): void; + +Commits the modification on the album attributes to the database. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +async function commitModifyDemoCallback() { + console.info('commitModifyDemo') + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE; + let getImageOp = { + selections: '', + selectionArgs: [], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); + let asset = await fetchFileResult.getFirstObject(); + console.info('old displayName:', asset.displayName) + asset.displayName = 'newDisplayName'; + console.info('new displayName:', asset.displayName) + asset.commitModify((err) => { + if (err == undefined) { + console.info('commitModify succeed.') + } else { + console.info('commitModify failed, message =', err); + } + }); +} +``` + +### commitModify + +commitModify(): Promise<void>; + +Commits the modification on the album attributes to the database. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------ | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +async function commitModifyDemoPromise() { + console.info('commitModifyDemo') + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE; + let getImageOp = { + selections: '', + selectionArgs: [], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); + let asset = await fetchFileResult.getFirstObject(); + console.info('old displayName:', asset.displayName) + asset.displayName = 'newDisplayName'; + console.info('new displayName:', asset.displayName) + try { + await asset.commitModify(); + console.info('commitModify succeed.') + } catch (err) { + console.info('commitModify failed, message =', err); + } +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, callback: AsyncCallback<FetchFileResult>): void; + +Obtains the file assets in this album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function albumGetFileAssetsDemoCallback() { + console.info('albumGetFileAssetsDemoCallback2') + let imageType = userfile_manager.MediaType.IMAGE; + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); + const album = albumList[0]; + album.getFileAssets([imageType], (err, albumFetchFileResult) => { + if (err == undefined) { + console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + } else { + console.info("getFileAssets failed with error:"+ err); + } + }); +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; + +Obtains the file assets in this album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the media data. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function albumGetFileAssetsDemoCallback() { + console.info('albumGetFileAssetsDemoCallback') + let imageType = userfile_manager.MediaType.IMAGE; + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } + const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); + const album = albumList[0]; + album.getFileAssets([imageType], fileNoArgsfetchOp, (err, albumFetchFileResult) => { + if (err == undefined) { + console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + } else { + console.info("getFileAssets failed with error:"+ err); + } + }); + } +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options?: MediaFetchOptions): Promise<FetchFileResult>; + +Obtains the file assets in this album. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the media data.| + +**Return value** + +| Type | Description | +| --------------------------------------------- | ------------------------- | +| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| + +**Example** + +```ts +async function albumGetFileAssetsDemoPromise() { + console.info('albumGetFileAssetsDemoPromise') + let imageType = userfile_manager.MediaType.IMAGE; + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } + const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); + const album = albumList[0]; + album.getFileAssets([imageType], fileNoArgsfetchOp).then(function(albumFetchFileResult){ + console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + }).catch(function(err){ + console.info("getFileAssets failed with error:"+ err); + }); +} +``` +## VirtualAlbum +Provides APIs for managing a virtual album. + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; + +Obtains file assets in the virtual album. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +> **NOTE**
+> The ability privilege level (APL) of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the Access Control List (ACL). For details, see [ACL](../../security/accesstoken-overview.md#acl). +> +> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function virtualAlbumGetFileAssetsDemoCallback() { + console.info('virtualAlbumGetFileAssetsDemoCallback') + try { + var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); + } catch (err) { + console.info('getPrivateAlbum failed, message = ', err); + } + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + + trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt, (err, fetchResult) => { + if (err == undefined) { + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); + } else { + console.info('getFileAssets failed, message = ', err); + } + }); +} +``` + +### getFileAssets +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; + +Obtains file assets in the virtual album. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +> **NOTE**
+> The APL of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the ACL. For details, see [ACL](../../security/accesstoken-overview.md#acl). +> +> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the files.| + +**Return value** + +| Type | Description | +| --------------------------------------------- | ------------------------- | +| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| + +**Example** + +```ts +async function virtualAlbumGetFileAssetsDemoPromise() { + console.info('virtualAlbumGetFileAssetsDemoPromise') + let albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + + let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); +} +``` + +## PeerInfo + +Describes information about a registered device. +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +| Name | Type | Readable| Writable| Description | +| ---------- | -------------------------- | ---- | ---- | ---------------- | +| deviceName | string | Yes | No | Name of the registered device. | +| networkId | string | Yes | No | Network ID of the registered device.| +| isOnline | boolean | Yes | No | Whether the registered device is online. | + +## MediaType + +Enumerates the media types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Description| +| ----- | ---- | +| FILE | File.| +| IMAGE | Image.| +| VIDEO | Video.| +| AUDIO | Audio.| + +## FileKey + +Defines the key file information. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | File URI. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | File name displayed. | +| 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 last modified. The value is the number of seconds elapsed since the Epoch time. | +| TITLE | title | Title in the file. | + +## AudioKey + +Defines the key information about an audio file. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | Promise used to return the URI of the file created. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | File name displayed. | +| 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 last modified. The value is the number of seconds elapsed since the Epoch time. | +| TITLE | title | Title in the file. | +| ARTIST | artist | Author of the file. | +| AUDIOALBUM | audio_album | Audio album. | +| DURATION | duration | Duration, in ms. | + +## ImageVideoKey + +Defines the key information about an image or video file. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | File URI. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | File name displayed. | +| 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 last modified. The value is the number of seconds elapsed since the Epoch time. | +| DURATION | duration | Duration, in ms. | +| WIDTH | width | Image width, in pixels. | +| HEIGHT | height | Image height, in pixels. | +| DATE_TAKEN | date_taken | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | + +## AlbumKey + +Defines the key album information. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | Album URI. | +| RELATIVE_PATH | relative_path | Relative public directory of the album. | +| DISPLAY_NAME | display_name | Album name displayed. | +| DATE_ADDED | date_added | Date when the album was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the album was last modified. The value is the number of seconds elapsed since the Epoch time. | + +## DirectoryType + +Enumerates directory types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Description | +| ------------- | ------------------ | +| DIR_CAMERA | Directory of camera files.| +| DIR_VIDEO | Directory of video files. | +| DIR_IMAGE | Directory of image files. | +| DIR_AUDIO | Directory of audio files. | +| DIR_DOCUMENTS | Directory of documents. | +| DIR_DOWNLOAD | Download directory. | + +## MediaFetchOptions + +Defines the options for fetching media files. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable| Writable| Mandatory| Description | +| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| selections | string | Yes | Yes | Yes | Conditions for fetching files. The 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 | Values of the conditions specified in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | + +## Size + +Defines the image size. +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | -------- | +| width | number | Yes | Yes | Image width, in pixels.| +| height | number | Yes | Yes | Image height, in pixels.| + +## VirtualAlbumType +Enumerates the system or virtual album types. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Description | +| ------------- | ------------------ | +| TYPE_FAVORITE | Favorites album.
This is a system API.| +| TYPE_TRASH | Trash album.
This is a system API.| diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index eb52d85a2c418842f2cb2d581fb0583917b68622..9d8332040bdcfece8717aacd79ea2eb579686cdd 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -75,7 +75,7 @@ Obtains detailed information about a system error code. callbackWrapper(original: Function): (err: Object, value: Object )=>void -Calls back an asynchronous function. In the callback, the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved), and the second parameter indicates the resolved value. +Wraps an asynchronous function (or a function that returns a promise) into an error-first callback, which means that **(err, value) => ...** is used as the last parameter of the callback. In the callback, the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved), and the second parameter indicates the resolved value. **System capability**: SystemCapability.Utils.Lang @@ -110,9 +110,10 @@ Calls back an asynchronous function. In the callback, the first parameter indica promiseWrapper(original: (err: Object, value: Object) => void): Object > **NOTE** +> > This API is deprecated since API version 9. You are advised to use **[util.promisify9+](#utilpromisify9)** instead. -Processes an asynchronous function and returns a promise version. +Wraps a function that follows the error-first callback paradigm into a promise. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 8d0c0ad48f1dc919c5032dc1d37ad39026071583..95654a5829967c3e6f3be2be8c5daf3baf527386 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -13,11 +13,11 @@ The **Vibrator** module provides APIs for triggering or stopping vibration. import vibrator from '@ohos.vibrator'; ``` -## vibrator.vibrate +## vibrator.startVibration9+ -vibrate(duration: number): Promise<void> +startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void -Triggers vibration with the specified duration. This API uses a promise to return the result. +Triggers vibration with the specified effect and attribute. This API uses a promise to return the result. **Required permissions**: ohos.permission.VIBRATE @@ -25,29 +25,45 @@ Triggers vibration with the specified duration. This API uses a promise to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| duration | number | Yes | Vibration duration, in ms.| +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | :--------------------------------------------------------- | +| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. | +| attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | +| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| -**Return value** +**Error codes** -| Type | Description | -| ------------------- | -------------------------------------- | -| Promise<void> | Promise that returns no value.| +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| **Example** - ```js - vibrator.vibrate(1000).then(()=>{ - console.log("Promise returned to indicate a successful vibration."); - }, (error)=>{ - console.log("error.code"+error.code+"error.message"+error.message); - }); - ``` +```js +try { + vibrator.startVibration({ + type:'time', + duration:1000, + },{ + id:0, + usage: 'alarm' + }, (error)=>{ + if(error){ + console.log('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + }else{ + console.log('Callback returned to indicate a successful vibration.'); + } + }); +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -## vibrator.vibrate9+ +## vibrator.startVibration9+ -vibrate(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> +startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> Triggers vibration with the specified effect and attribute. This API uses a promise to return the result. @@ -58,7 +74,7 @@ Triggers vibration with the specified effect and attribute. This API uses a prom **Parameters** | Name | Type | Mandatory| Description | -| --------- | -------------------------------------- | ---- | :------------- | +| --------- | -------------------------------------- | ---- | -------------- | | effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect.| | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute.| @@ -68,148 +84,70 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | ------------------- | -------------------------------------- | | Promise<void> | Promise that returns no value.| -**Example** - -```js -vibrator.vibrate({ - type: 'time', - duration: 1000 -}, { - id: 0, - usage: 'alarm' -}).then(()=>{ - console.log("Promise returned to indicate a successful vibration"); -}).catch((error)=>{ - console.log("error.code" + error.code + "error.message" + error.message); -}) -``` - -## vibrator.vibrate +**Error codes** -vibrate(duration: number, callback?: AsyncCallback<void>): void - -Triggers vibration with the specified duration. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.VIBRATE - -**System capability**: SystemCapability.Sensors.MiscDevice +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------------------------------- | -| duration | number | Yes | Vibration duration, in ms. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| **Example** ```js - vibrator.vibrate(1000,function(error){ - if(error){ - console.log("error.code" + error.code + "error.message" + error.message); - }else{ - console.log("Callback returned to indicate a successful vibration."); - } - }) +try { + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' + }).then(()=>{ + console.log('Promise returned to indicate a successful vibration'); + }).catch((error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); + }) +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` +## vibrator.stopVibration9+ -## vibrator.vibrate +stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void -vibrate(effectId: EffectId): Promise<void> - -Triggers vibration with the specified effect. This API uses a promise to return the result. +Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. **Required permissions**: ohos.permission.VIBRATE **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID.| - -**Return value** -| Type | Description | -| ------------------- | -------------------------------------- | -| Promise<void> | Promise that returns no value.| -**Example** - ```js - vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ - console.log("Promise returned to indicate a successful vibration."); - }, (error)=>{ - console.log("error.code" + error.code + "error.message" + error.message); - }); - ``` - - -## vibrator.vibrate - -vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void - -Triggers vibration with the specified effect. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.VIBRATE - -**System capability**: SystemCapability.Sensors.MiscDevice - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------------------------------- | -| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | +| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** ```js - vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ - if(error){ - console.log("error.code" + error.code + "error.message" + error.message); - }else{ - console.log("Callback returned to indicate a successful vibration."); - } - }) +try { + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate successful.'); + } + }) +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## vibrator.vibrate9+ - -vibrate(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void - -Triggers vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.VIBRATE - -**System capability**: SystemCapability.Sensors.MiscDevice +## vibrator.stopVibration9+ -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | -------------------------------------- | ---- | :--------------------------------------------------------- | -| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. | -| attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | -| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| - -**Example** - -```js -vibrator.vibrate({ - type:'time', - duration:1000, -},{ - id:0, - usage: 'alarm' -}, (error)=>{ - if(error){ - console.log("vibrate fail, error.code:" + error.code + ",error.message:" + error.message); - }else{ - console.log("Callback returned to indicate a successful vibration."); - } -}); -``` - -## vibrator.stop - -stop(stopMode: VibratorStopMode): Promise<void> +stopVibration(stopMode: VibratorStopMode): Promise<void> Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. @@ -218,6 +156,7 @@ Stops the vibration with the specified **stopMode**. This API uses a promise to **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ------------------------ | | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration.| @@ -231,43 +170,17 @@ Stops the vibration with the specified **stopMode**. This API uses a promise to **Example** ```js - vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ - console.log("Promise returned to indicate a successful vibration."); - }, (error)=>{ - console.log("error.code" + error.code + "error.message" + error.message); - }); +try { + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); + }, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); + }); +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` - -## vibrator.stop - -stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void; - -Stops the vibration with the specified **stopMode**. This API uses an asynchronous callback to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. - -**Required permissions**: ohos.permission.VIBRATE - -**System capability**: SystemCapability.Sensors.MiscDevice - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| - -**Example** - - ```js - vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ - if(error){ - console.log("error.code" + error.code + "error.message" + error.message); - }else{ - console.log("Callback returned to indicate a successful stop."); - } - }) - ``` - - ## EffectId Describes the vibration effect ID. @@ -352,3 +265,201 @@ Enumerates the vibration scenarios. | media | string | Multimedia vibration scenario. | | physicalFeedback | string | Physical feedback vibration scenario. | | simulateReality | string | Simulated reality vibration scenario. | + +## vibrator.vibrate(deprecated) + +vibrate(duration: number): Promise<void> + +Triggers vibration with the specified duration. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9-1) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| duration | number | Yes | Vibration duration, in ms.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +vibrator.vibrate(1000).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); +}, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); +}); + ``` + +## vibrator.vibrate(deprecated) + +vibrate(duration: number, callback?: AsyncCallback<void>): void + +Triggers vibration with the specified duration. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------------- | +| duration | number | Yes | Vibration duration, in ms. | +| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + + ```js +vibrator.vibrate(1000,function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate a successful vibration.'); + } +}) + ``` + + +## vibrator.vibrate(deprecated) + +vibrate(effectId: EffectId): Promise<void> + +Triggers vibration with the specified effect. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9-1) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------ | +| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); +}, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); +}); + ``` + + +## vibrator.vibrate(deprecated) + +vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void + +Triggers vibration with the specified effect. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------------- | +| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID. | +| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + + ```js +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate a successful vibration.'); + } +}) + ``` + +## vibrator.stop(deprecated) + +stop(stopMode: VibratorStopMode): Promise<void> + +Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. + +This API is deprecated since API version 9. You are advised to use [vibrator.stopVibration](#vibratorstopvibration9-1) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------ | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); +}, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); +}); + ``` + + +## vibrator.stop(deprecated) + +stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void + +Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. + +This API is deprecated since API version 9. You are advised to use [vibrator.stopVibration](#vibratorstopvibration9) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | +| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + + ```js +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate successful.'); + } +}) + ``` diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md index 87cfad2f83ba3c25d4ab90a874777d86bb2cd473..79cbf5db12746acc8e18d293c03fe3aa48bdc86a 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-volumemanager.md @@ -52,7 +52,7 @@ Asynchronously obtains information about all available volumes. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback:AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| + | callback | callback: AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| **Example** @@ -110,7 +110,7 @@ Asynchronously obtains the available space of the specified volume. This API use | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | callback: AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| **Example** @@ -154,7 +154,7 @@ Asynchronously unmounts a volume. This API uses a promise to return the result. ## volumemanager.unmount -unmount(volumeId: string, callback:AsyncCallback<boolean>):void +unmount(volumeId: string, callback: AsyncCallback<boolean>): void Asynchronously unmounts a volume. This API uses a callback to return the result. @@ -167,7 +167,7 @@ Asynchronously unmounts a volume. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | callback: AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| **Example** @@ -226,7 +226,7 @@ Asynchronously obtains volume information based on the UUID. This API uses a cal | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------- | | uuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + | callback | callback: AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| **Example** @@ -347,7 +347,7 @@ Asynchronously sets the volume description based on the UUID. This API uses a ca | ---------- | --------------------------------------- | ---- | ---------------- | | uuid | string | Yes | UUID of the volume. | | description | string | Yes | Volume description. | - | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result.| + | callback | callback: AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -410,7 +410,7 @@ Asynchronously formats a volume. This API uses a callback to return the result. | -------- | ------------------------- | ---- | ----------------------------- | | volumeId | string | Yes | Volume ID. | | fsType | string | Yes | File system type.| - | callback | callback:AsyncCallback<void> | Yes | Called after the volume is formatted. | + | callback | callback: AsyncCallback<void> | Yes | Called after the volume is formatted. | **Example** @@ -473,7 +473,7 @@ Asynchronously partitions a disk. This API uses a callback to return the result. | -------- | --------------------------------------- | ---- | ---------------- | | diskId | string | Yes | ID of the disk to which the volume belongs. | | type | number | Yes | Partition type. | - | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result. | + | callback | callback: AsyncCallback<void> | Yes | Callback invoked 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 52f5367110bc35c33075ed291a796a657a468816..bda4ad227b32b18130682bb4fe10db9a446535ec 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -433,7 +433,7 @@ ws.off('open', callback1); on\(type: 'message', callback: AsyncCallback\): void -Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). @@ -462,7 +462,7 @@ ws.on('message', (err, value) => { off\(type: 'message', callback?: AsyncCallback\): void -Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 7f5b41145c5831f3ecd0014687a52366b598f9d4..a8221a78898accf8d18724193df311a13693b998 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -25,9 +25,9 @@ Enables WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.disableWifi @@ -44,9 +44,9 @@ Disables WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.isWifiActive @@ -61,9 +61,9 @@ Checks whether WLAN is enabled. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| ## wifi.scan @@ -78,9 +78,9 @@ Starts a scan for WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getScanInfos @@ -95,9 +95,9 @@ Obtains the scan result. This API uses a promise to return the result. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| ## wifi.getScanInfos @@ -112,9 +112,9 @@ Obtains the scan result. This API uses an asynchronous callback to return the re **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| **Example** ```js @@ -247,9 +247,9 @@ Obtains the scan result. This API returns the result synchronously. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| ## wifi.addDeviceConfig @@ -266,15 +266,15 @@ Adds network configuration. This API uses a promise to return the result. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| ## WifiDeviceConfig @@ -302,7 +302,7 @@ Represents the WLAN configuration. ## IpType7+ -Enumerate the IP address types. +Enumerates the IP address types. **System API**: This is a system API. @@ -412,10 +412,10 @@ Adds network configuration. This API uses an asynchronous callback to return the **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| ## wifi.addUntrustedConfig7+ @@ -430,15 +430,15 @@ Adds the configuration of an untrusted network. This API uses a promise to retur **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.addUntrustedConfig7+ @@ -453,10 +453,10 @@ Adds the configuration of an untrusted network. This API uses an asynchronous ca **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| ## wifi.removeUntrustedConfig7+ @@ -471,15 +471,15 @@ Removes the configuration of an untrusted network. This API uses a promise to re **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.removeUntrustedConfig7+ @@ -494,10 +494,10 @@ Removes the configuration of an untrusted network. This API uses an asynchronous **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| -| callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| ## wifi.addCandidateConfig9+ @@ -512,15 +512,15 @@ Adds the configuration of a candidate network. This API uses a promise to return **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<number> | Promise used to return the network configuration ID.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| ## wifi.addCandidateConfig9+ @@ -535,10 +535,10 @@ Adds the configuration of a candidate network. This API uses an asynchronous cal **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| ## wifi.removeCandidateConfig9+ @@ -553,15 +553,15 @@ Removes the configuration of a candidate network. This API uses a promise to ret **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | networkId | number | Yes| ID of the network configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| ## wifi.removeCandidateConfig9+ @@ -576,8 +576,8 @@ Removes the configuration of a candidate network. This API uses an asynchronous **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | networkId | number | Yes| ID of the network configuration to remove.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| @@ -594,9 +594,9 @@ Obtains candidate network configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| ## wifi.connectToCandidateConfig9+ @@ -611,9 +611,9 @@ Connects to a candidate network. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the candidate network configuration.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| ## wifi.connectToNetwork @@ -630,15 +630,15 @@ Connects to the specified network. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| Network configuration ID.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| Network configuration ID.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.connectToDevice @@ -656,15 +656,15 @@ Connects to the specified network. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.disconnect @@ -682,9 +682,9 @@ Disconnects the network. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getSignalLevel @@ -699,16 +699,16 @@ Obtains the WLAN signal level. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| rssi | number | Yes| RSSI of the hotspot, in dBm.| -| band | number | Yes| Frequency band of the WLAN AP.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | rssi | number | Yes| RSSI of the hotspot, in dBm.| + | band | number | Yes| Frequency band of the WLAN AP.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | Signal level obtained. The value range is [0, 4].| + | **Type**| **Description**| + | -------- | -------- | + | number | Signal level obtained. The value range is [0, 4].| ## wifi.getLinkedInfo @@ -723,9 +723,9 @@ Obtains WLAN connection information. This API uses a promise to return the resul **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| ## wifi.getLinkedInfo @@ -740,9 +740,9 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -844,9 +844,9 @@ Checks whether the WLAN is connected. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| ## wifi.getSupportedFeatures7+ @@ -863,9 +863,9 @@ Obtains the features supported by this device. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | Feature value. | + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value. | **Feature IDs** @@ -896,15 +896,15 @@ Checks whether the device supports the specified WLAN feature. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| featureId | number | Yes| Feature ID.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| ## wifi.getDeviceMacAddress7+ @@ -921,9 +921,9 @@ Obtains the device MAC address. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| string[] | MAC address obtained.| + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| ## wifi.getIpInfo7+ @@ -938,9 +938,9 @@ Obtains IP information. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| [IpInfo](#ipinfo7) | IP information obtained.| + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo7) | IP information obtained.| ## IpInfo7+ @@ -972,9 +972,9 @@ Obtains the country code. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| string | Country code obtained.| + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| ## wifi.reassociate7+ @@ -991,9 +991,9 @@ Re-associates with the network. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.reconnect7+ @@ -1010,9 +1010,9 @@ Reconnects to the network. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getDeviceConfigs7+ @@ -1029,9 +1029,9 @@ Obtains network configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| ## wifi.updateNetwork7+ @@ -1048,15 +1048,15 @@ Updates network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| + | **Type**| **Description**| + | -------- | -------- | + | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| ## wifi.disableNetwork7+ @@ -1073,15 +1073,15 @@ Disables network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| netId | number | Yes| ID of the network configuration to disable.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the network configuration to disable.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.removeAllNetwork7+ @@ -1098,9 +1098,9 @@ Removes the configuration of all networks. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.removeDevice7+ @@ -1117,15 +1117,15 @@ Removes the specified network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | id | number | Yes| ID of the network configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.enableHotspot7+ @@ -1142,9 +1142,9 @@ Enables this hotspot. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.disableHotspot7+ @@ -1161,9 +1161,9 @@ Disables this hotspot. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.isHotspotDualBandSupported7+ @@ -1180,9 +1180,9 @@ Checks whether the hotspot supports dual band. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| ## wifi.isHotspotActive7+ @@ -1199,9 +1199,9 @@ Checks whether this hotspot is active. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| ## wifi.setHotspotConfig7+ @@ -1218,15 +1218,15 @@ Sets hotspot configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## HotspotConfig7+ @@ -1260,9 +1260,9 @@ obtains hotspot configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| ## wifi.getStations7+ @@ -1279,9 +1279,9 @@ Obtains information about the connected stations. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| ## StationInfo7+ @@ -1311,9 +1311,9 @@ Obtains P2P link information. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| @@ -1354,9 +1354,9 @@ Obtains P2P link information. This API uses an asynchronous callback to return t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| ## wifi.getCurrentGroup8+ @@ -1371,9 +1371,9 @@ Obtains the current P2P group information. This API uses a promise to return the **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| ## wifi.getCurrentGroup8+ @@ -1388,9 +1388,9 @@ Obtains the current P2P group information. This API uses an asynchronous callbac **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| ## wifi.getP2pPeerDevices8+ @@ -1405,9 +1405,9 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| ## wifi.getP2pPeerDevices8+ @@ -1422,9 +1422,9 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| ## WifiP2pDevice8+ @@ -1469,9 +1469,9 @@ Obtains the local device information in the P2P connection. This API uses a prom **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| ## wifi.getP2pLocalDevice9+ @@ -1486,9 +1486,9 @@ Obtains the local device information in the P2P connection. This API uses an asy **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| ## wifi.createGroup8+ @@ -1503,15 +1503,15 @@ Creates a P2P group. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## WifiP2PConfig8+ @@ -1554,9 +1554,9 @@ Removes this P2P group. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.p2pConnect8+ @@ -1572,15 +1572,15 @@ Sets up a P2P connection. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -1662,9 +1662,9 @@ Cancels this P2P connection. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.startDiscoverDevices8+ @@ -1679,9 +1679,9 @@ Starts to discover devices. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.stopDiscoverDevices8+ @@ -1696,9 +1696,9 @@ Stops discovering devices. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.deletePersistentGroup8+ @@ -1716,15 +1716,15 @@ Deletes a persistent group. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| netId | number | Yes| ID of the group to delete.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the group to delete.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getP2pGroups9+ @@ -1741,9 +1741,9 @@ Obtains information about all P2P groups. This API uses a promise to return the **Return value** -| Type| Description| -| -------- | -------- | -| Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| ## WifiP2pGroupInfo8+ @@ -1779,9 +1779,9 @@ Obtains information about all P2P groups. This API uses an asynchronous callback **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| ## wifi.setDeviceName8+ @@ -1798,15 +1798,15 @@ Sets the device name. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| devName | string | Yes| Device name to set.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | devName | string | Yes| Device name to set.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.on('wifiStateChange')7+ @@ -1821,10 +1821,10 @@ Registers the WLAN state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| **WLAN states** @@ -1848,10 +1848,10 @@ Unregisters the WLAN state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiStateChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -1881,10 +1881,10 @@ Registers the WLAN connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiConnectionChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| **WLAN connection states** @@ -1906,10 +1906,10 @@ Unregisters the WLAN connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiConnectionChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -1924,10 +1924,10 @@ Registers the WLAN scan state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| **WLAN scan states** @@ -1952,7 +1952,7 @@ Unregisters the WLAN scan state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiRssiChange')7+ @@ -1967,10 +1967,10 @@ Registers the RSSI change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| ## wifi.off('wifiRssiChange')7+ @@ -1985,10 +1985,10 @@ Unregisters the RSSI change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('hotspotStateChange')7+ @@ -2003,10 +2003,10 @@ Registers the hotspot state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| **Hotspot states** @@ -2030,10 +2030,10 @@ Unregisters the hotspot state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pStateChange')8+ @@ -2048,10 +2048,10 @@ Registers the P2P state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| **P2P states** @@ -2075,10 +2075,10 @@ Unregisters the P2P state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pConnectionChange')8+ @@ -2093,10 +2093,10 @@ Registers the P2P connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pConnectionChange**.| -| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the P2P connection state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the P2P connection state.| ## wifi.off('p2pConnectionChange')8+ @@ -2111,10 +2111,10 @@ Unregisters the P2P connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pConnectionChange**.| -| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| +| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDeviceChange')8+ @@ -2129,10 +2129,10 @@ Registers the P2P device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDeviceChange**.| -| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P device state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P device state.| ## wifi.off('p2pDeviceChange')8+ @@ -2147,10 +2147,10 @@ Unregisters the P2P device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDeviceChange**.| -| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| +| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPeerDeviceChange')8+ @@ -2165,9 +2165,9 @@ Registers the P2P peer device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P peer device state.| @@ -2183,10 +2183,10 @@ Unregisters the P2P peer device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| -| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ @@ -2201,10 +2201,10 @@ Registers the P2P persistent group state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| -| callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| ## wifi.off('p2pPersistentGroupChange')8+ @@ -2219,10 +2219,10 @@ Unregisters the P2P persistent group state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| -| callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| +| callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDiscoveryChange')8+ @@ -2237,10 +2237,10 @@ Registers the P2P device discovery state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| **P2P discovered device states** @@ -2262,7 +2262,7 @@ Unregisters the P2P device discovery state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| -| callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| +| callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 5aa129293c705d4c8c9ce5eaf78ac2a6f7960662..3ef92adc2a423c2d0871f303faaabb395faf8003 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -30,9 +30,7 @@ Provides options that can be set for the **Worker** instance to create. | Name | Type | Readable| Writable| Description | | ------ | --------- | ---- | ---- | ---------------------- | -| type | "classic" | Yes | Yes | Mode in which the worker thread executes the script.| | name | string | Yes | Yes | Name of the worker thread. | -| shared | boolean | Yes | Yes | Whether the worker can be shared.| ## Worker @@ -52,7 +50,7 @@ A constructor used to create a **Worker** instance. | Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| scriptURL | string | Yes | URL of the script to be executed by the worker thread.
In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:
(a) The **workers** directory is at the same level as the **pages** directory.
(b) The **workers** directory is at a different level from the **pages** directory. +| scriptURL | string | Yes | Directory of the script to be executed by the **Worker** instance.
In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:
(a) The script directory is at the same level as the **pages** directory.
(b) The script directory is at a different level from the **pages** directory. | options | [WorkerOptions](#workeroptions) | No | Options that can be set for the **Worker** instance. | **Return value** @@ -65,25 +63,26 @@ A constructor used to create a **Worker** instance. ```js import worker from '@ohos.worker'; -// Create a worker thread. +// Create a Worker instance. -// In the FA model, the workers and pages directories are at the same level. -const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker"}); -// In the FA model, the workers and pages directories are at different levels. -const workerFAModel02 = new worker.Worker("../workers/worker.js", {name:"first worker"}); +// In the FA model, the worker script directory and pages directory are at the same level. +const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker in FA model"}); +// In the FA model, the worker script directory and pages directory are at different levels. +const workerFAModel02 = new worker.Worker("../workers/worker.js"); -// In the stage model, the workers and pages directories are at the same level. -const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts'); -// In the stage model, the workers and pages directories are at different levels. +// In the stage model, the worker script directory and pages directory are at the same level. +const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); +// In the stage model, the worker script directory and pages directory are at different levels. const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts'); -// scriptURL—— Description of "entry/ets/workers/worker.ts". +// For the script URL "entry/ets/workers/worker.ts" in the stage model: // entry is the value of the name attribute under module in the module.json5 file. // ets indicates the programming language in use. ``` -Depending on whether the works and pages directories are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. +Depending on whether the worker script directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. + +(1) The worker script directory and **pages** directory are at the same level. -(1) If the workers and pages directories are at the same level, the configuration is optional. In the FA model: ```json @@ -105,7 +104,8 @@ In the stage model: } } ``` -(2) If the workers and pages directories are at different levels, the configuration is mandatory. +(2) The worker script directory and **pages** directory are at different levels. + In the FA model: ```json "buildOption": { @@ -130,7 +130,7 @@ In the stage model: postMessage(message: Object, options?: PostMessageOptions): void -Sends a message to the worker thread. The message data is transferred using the structured clone algorithm. +Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). **System capability**: SystemCapability.Utils.Lang @@ -157,7 +157,7 @@ workerInstance.postMessage(buffer, [buffer]); on(type: string, listener: EventListener): void -Adds an event listener for the worker instance. +Adds an event listener for the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -166,7 +166,7 @@ Adds an event listener for the worker instance. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ---------------- | | type | string | Yes | Type of the event to listen for.| -| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | +| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | **Example** @@ -191,7 +191,7 @@ Adds an event listener for the worker thread and removes the event listener afte | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ---------------- | | type | string | Yes | Type of the event to listen for.| -| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | +| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | **Example** @@ -215,8 +215,8 @@ Removes an event listener for the worker thread. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ---------------------- | -| type | string | Yes | Type of the event for which the event listener is removed. | -| listener | [EventListener](#eventlistener) | No | Callback of the event listener to remove.| +| type | string | Yes | Type of the event for which the event listener is to be removed. | +| listener | [EventListener](#eventlistener) | No | Callback of the event listener to remove. | **Example** @@ -380,8 +380,8 @@ Removes an event listener for the worker thread. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ---------------------- | -| type | string | Yes | Type of the event for which the event listener is removed. | -| callback | [EventListener](#eventlistener) | No | Callback of the event listener to remove.| +| type | string | Yes | Type of the event for which the event listener is to be removed.| +| callback | [EventListener](#eventlistener) | No | Callback of the event listener to remove. | **Example** @@ -437,7 +437,7 @@ workerInstance.removeAllListener(); ## DedicatedWorkerGlobalScope -Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [WorkerGlobalScope](#workerglobalscope). +Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscope). ### postMessage @@ -507,7 +507,7 @@ parentPort.onmessage = function(e) { onmessage?: (event: MessageEvent\) => void -Defines the event handler to be called when the worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the worker thread. +Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -591,12 +591,9 @@ Defines the event. ## EventListener -Implements event listening. - - -### (evt: Event): void | Promise<void> +(evt: Event): void | Promise<void> -Specifies the callback to invoke. +Implements event listening. **System capability**: SystemCapability.Utils.Lang @@ -692,23 +689,107 @@ parentPort.onerror = function(e){ } ``` +## More Information + +### Sequenceable Data Types +| Type | Remarks | Supported | +| ------------------- | -------------------------------------------------------- | -------------------- | +| All primitive types | The Symbol type is not included. | Yes | +| Date | | Yes | +| String | | Yes | +| RegExp | | Yes | +| Array | | Yes | +| Map | | Yes | +| Set | | Yes | +| Object | Only plain objects are supported. Objects with functions are not supported. | Yes | +| ArrayBuffer | The transfer capability is provided. | Yes | +| TypedArray | | Yes | + +Exception: When an object created through a custom class is passed, no serialization error occurs. However, the attributes (such as Function) of the custom class cannot be passed through serialization. +```js +// main.js +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("message from main to worker"); +workerInstance.onmessage = function(d) { + // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. + let data = d.data; +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort; +class MyModel { + Init() { + this.name = "wzy" + this.age = 18 + } + SetName() { + this.name = "WZY" + } +} +parentPort.onmessage = function(d) { + console.log("worker.js onmessage"); + let data = d.data; + let func1 = function() { + console.log("post message is function"); + } + let obj1 = { + "index": 2, + "name1": "zhangshan", + setName() { + this.index = 3; + } + } + let obj2 = new MyModel(); + // parentPort.postMessage(func1); A serialization error occurs when passing func1. + // parentPort.postMessage(obj1); A serialization error occurs when passing obj1. + parentPort.postMessage(obj2); // No serialization error occurs when passing obj2. +} +parentPort.onmessageerror = function(e) { + console.log("worker.js onmessageerror"); +} +parentPort.onerror = function(e) { + console.log("worker.js onerror"); +} +``` + +### Memory Model +The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through sequentialization. They complete computing tasks and return the result to the main thread. + +Each actor concurrently processes tasks of the main thread. For each actor, there is a message queue and a single-thread execution module. The message queue receives requests from the main thread and other actors; the single-thread execution module serially processes requests, sends requests to other actors, and creates new actors. These isolated actors use the asynchronous mode and can run concurrently. + +### Precautions +- Currently, a maximum of seven workers can co-exist. +- If the number of workers exceeds the upper limit, the error message "Too many workers, the number of workers exceeds the maximum." is displayed. +- To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance. +- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. + ## Sample Code ### FA Model ```js -// main.js (The following assumes that the workers and pages directories are at the same level.) +// main.js (The following assumes that the worker script directory and pages directory are at the same level.) import worker from '@ohos.worker'; +// Create a Worker instance in the main thread. const workerInstance = new worker.Worker("workers/worker.ts"); // Create either a .json or .ts file. // const workerInstance = new worker.Worker("workers/worker.js"); +// The main thread transfers information to the worker thread. workerInstance.postMessage("123"); + +// The main thread receives information from the worker thread. workerInstance.onmessage = function(e) { + // data carries the information sent by the worker thread. let data = e.data; console.log("main.js onmessage"); - // Call terminate after the worker thread receives messages. + + // Terminate the Worker instance. workerInstance.terminate(); } -// Call onexit. + +// Call onexit(). workerInstance.onexit = function() { console.log("main.js terminate"); } @@ -716,14 +797,21 @@ workerInstance.onexit = function() { ```js // worker.js import worker from '@ohos.worker'; + +// Create an object in the worker thread for communicating with the main thread. const parentPort = worker.parentPort +// The worker thread receives information from the main thread. parentPort.onmessage = function(e) { + // data carries the information sent by the main thread. let data = e.data; console.log("worker.js onmessage"); + + // The worker thread sends information to the main thread. parentPort.postMessage("123") } +// Trigger a callback when an error occurs in the worker thread. parentPort.onerror= function(e) { console.log("worker.js onerror"); } @@ -740,19 +828,27 @@ Configuration of the **build-profile.json5** file: ``` ### Stage Model ```js -// main.js (The following assumes that the workers and pages directories are at different levels.) +// main.js (The following assumes that the worker script directory and pages directory are at different levels.) import worker from '@ohos.worker'; + +// Create a Worker instance in the main thread. const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.ts"); // Create either a .json or .ts file. // const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.js"); + +// The main thread transfers information to the worker thread. workerInstance.postMessage("123"); + +// The main thread receives information from the worker thread. workerInstance.onmessage = function(e) { + // data carries the information sent by the worker thread. let data = e.data; console.log("main.js onmessage"); - // Call terminate after the worker thread receives messages. + + // Terminate the Worker instance. workerInstance.terminate(); } -// Call onexit. +// Call onexit(). workerInstance.onexit = function() { console.log("main.js terminate"); } @@ -760,14 +856,21 @@ workerInstance.onexit = function() { ```js // worker.js import worker from '@ohos.worker'; + +// Create an object in the worker thread for communicating with the main thread. const parentPort = worker.parentPort +// The worker thread receives information from the main thread. parentPort.onmessage = function(e) { + // data carries the information sent by the main thread. let data = e.data; console.log("worker.js onmessage"); + + // The worker thread sends information to the main thread. parentPort.postMessage("123") } +// Trigger a callback when an error occurs in the worker thread. parentPort.onerror= function(e) { console.log("worker.js onerror"); } @@ -782,7 +885,3 @@ Configuration of the **build-profile.json5** file: } } ``` - -## Precautions -Currently, a maximum of seven workers can co-exist. -If the number of workers exceeds the upper limit, the error message "Too many workers, the number of workers exceeds the maximum." is displayed. diff --git a/en/application-dev/reference/arkui-js/Readme-EN.md b/en/application-dev/reference/arkui-js/Readme-EN.md index 46e4b416c4bc0ee3389c493a540e2a7bb375bd3a..d14e06d8a3a83329a2a6e2b508508e03c93aea4c 100644 --- a/en/application-dev/reference/arkui-js/Readme-EN.md +++ b/en/application-dev/reference/arkui-js/Readme-EN.md @@ -1,4 +1,4 @@ -# JavaScript-based Web-like Development Paradigm +# JavaScript-compatible Web-like Development Paradigm - Universal Component Information - [Universal Attributes](js-components-common-attributes.md) diff --git a/en/application-dev/reference/arkui-js/figures/EventParameters.gif b/en/application-dev/reference/arkui-js/figures/EventParameters.gif new file mode 100644 index 0000000000000000000000000000000000000000..3012b0fe3edabe15d0b48373fb738b5c4879842d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/EventParameters.gif differ diff --git a/en/application-dev/reference/arkui-js/js-components-basic-button.md b/en/application-dev/reference/arkui-js/js-components-basic-button.md index 6e9378efe275d52ea6e28a4e51baa6170f5d6a7c..29061668cc3ddd2c59a2b057a97bb09970807693 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-button.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-button.md @@ -18,7 +18,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ---------------------- | ------- | ----- | ---- | ---------------------------------------- | -| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Different from the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| +| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| | value | string | - | No | Text value of the button. | | icon | string | - | No | Path of the button icon. The supported icon formats are JPG, PNG, and SVG. | | placement5+ | string | end | No | Position of the button icon in text. This attribute is valid only when **type** is not set. Available values are as follows:
- **start**: The button icon is at the beginning of the text.
- **end**: The button icon is at the end of the text.
- **top**: The button icon is at the top of the text.
- **bottom**: The button icon is at the bottom of the text.| @@ -34,27 +34,20 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | Name | Type | Default Value | Mandatory | Description | | ----------- | -------------------------- | --------------- | ---- | ---------------------------------------- | -| text-color | <color> | \#007dff
| No | Text color of the button. | -| font-size | <length> | 16px
| No | Font size of the button. | +| text-color | <color> | \#007dff | No | Text color of the button. | +| font-size | <length> | 16px | No | Font size of the button. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| | font-style | string | normal | No | Font style of the button. | -| font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the font specified by [Custom Font Styles](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | | icon-width | <length> | - | No | Width of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | icon-height | <length> | - | No | Height of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | radius | <length> | - | No | Corner radius of the button. For a circle button, this style takes precedence over **width** and **height** in the universal styles.| -> **NOTE** -> - For capsule buttons, border-related styles are not supported. -> -> - For circle buttons, text-related styles are not supported. -> -> - For text buttons, the font size is automatically adaptive, and **radius**, **width**, and **height** cannot be set. The **background-color** style is not supported when the background is completely transparent. - ### When the Button Type Is arc -In addition to the **background-color**, **opacity**, **display**, **visibility**, **position**, **[left|top|right|bottom]** styles in [Universal Styles](../arkui-js/js-components-common-styles.md), the following styles are supported. +In addition to the **background-color**, **opacity**, **display**, **visibility**, **position**, and **[left|top|right|bottom]** styles in [Universal Styles](../arkui-js/js-components-common-styles.md), the following styles are supported. | Name | Type | Default Value | Mandatory | Description | | ----------- | -------------------------- | ---------- | ---- | ---------------------------------------- | @@ -62,8 +55,8 @@ In addition to the **background-color**, **opacity**, **display**, **visibility* | font-size | <length> | 37.5px | No | Font size of the arc button. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings. | | font-style | string | normal | No | Font style of the arc button. | -| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the font specified by [Custom Font Styles](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | ## Events @@ -79,7 +72,7 @@ When the button type is **download**, the following methods are supported. | Name | Parameters | Description | | ----------- | ------------------------------ | ---------------------------------------- | -| setProgress | { progress:percent } | Progress bar of the download button. The value ranges from 0 to 100. The progress bar is displayed if the value is greater than 0. If the value is greater than or equal to 100, the progress bar is not displayed.
The text displayed on the progress bar is subject to the **value** settings.| +| setProgress | { progress:percent } | Progress bar of the download button. The value ranges from 0 to 100. The progress bar is displayed if the value is greater than 0. If the value is greater than or equal to 100, the progress bar is not displayed.
The text displayed on the progress bar is subject to the **value** settings.| ## Example diff --git a/en/application-dev/reference/arkui-js/js-components-basic-chart.md b/en/application-dev/reference/arkui-js/js-components-basic-chart.md index b674facb9f71daaa97403e865feb983cc3e6dc7c..26ac1ef03d97536474103465f8f61cc5108ab126 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-chart.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-chart.md @@ -1,1158 +1,355 @@ -# chart +# chart -The **** component displays line charts, gauge charts, and bar charts. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component displays line charts, gauge charts, and bar charts. -None - -## Child Component - -Not supported - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

line

-

No

-

Chart type. Dynamic modification is not supported. Available values include:

-
  • bar: bar chart
  • line: line chart
  • gauge: gauge chart
  • progress5+: circle chart of progresses
  • loading5+: circle chart of loading processes
  • rainbow5+: circle chart of proportions
-

options

-

ChartOptions

-

-

-

No

-

Chart parameters. You must set parameters for bar charts and line charts. Parameter settings for gauge charts do not take effect. You can set the minimum value, maximum value, scale, and line width of the x-axis or y-axis, whether to display the x-axis and y-axis, and whether the line is smooth. Dynamic modification is not supported.

-

datasets

-

Array<ChartDataset>

-

-

-

No

-

Data set. You must set data sets for bar charts and line charts. Data set for a gauge chart does not take effect. You can set multiple datasets and their background colors.

-

segments5+

-

DataSegment | Array<DataSegment>

-

-

-

No

-

Data structures used by progress, loading, and rainbow charts.

-

DataSegment is available for progress and loading charts.

-

Array<DataSegment> is available for rainbow charts. A maximum of nine DataSegment are supported in the array.

-
NOTE:

-
-

effects5+

-

boolean

-

true

-

No

-

Whether to enable the effects for progress and rainbow charts.

-
NOTE:

-
-

animationduration6+

-

number

-

3000

-

No

-

Animation duration for expanding a rainbow chart, in milliseconds.

-
NOTE:

-
-
- -**Table 1** ChartOptions - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

xAxis

-

ChartAxis

-

-

-

Yes

-

X-axis parameters. You can set the minimum value, maximum value, and scale of the x-axis, and whether to display the x-axis.

-

yAxis

-

ChartAxis

-

-

-

Yes

-

Y-axis parameters. You can set the minimum value, maximum value, and scale of the y-axis, and whether to display the y-axis.

-

series

-

ChartSeries

-

-

-

No

-

Data sequence parameters.

-
  • Line style, such as the line width and whether the line is smooth.
  • Style and size of the white point at the start of the line.
-
NOTE:

Only line charts support this attribute.

-
-
- -**Table 2** ChartDataset - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

strokeColor

-

<color>

-

#ff6384

-

No

-

Line color.

-
NOTE:

Only line charts support this attribute.

-
-

fillColor

-

<color>

-

#ff6384

-

No

-

Fill color. For line charts, the value indicates the gradient color to fill.

-

data

-

Array<number> | Array<Point>5+

-

-

-

Yes

-

Data of the drawn line or bar.

-

gradient

-

boolean

-

false

-

No

-

Whether to display the gradient color.

-
NOTE:

Only line charts support this attribute.

-
-
- -**Table 3** ChartAxis - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

min

-

number

-

0

-

No

-

Minimum value of the axis.

-
NOTE:

Only line charts support negative numbers.

-
-

max

-

number

-

100

-

No

-

Maximum value of the axis.

-
NOTE:

Only line charts support negative numbers.

-
-

axisTick

-

number

-

10

-

No

-

Number of scales displayed on the axis.

-
NOTE:

The value ranges from 1 to 20. The display effect depends on the calculation result of Number of pixels occupied by the image width/(max-min).

-

In the bar chart, the number of bars in each group of data is the same as the number of scales, and the bars are displayed at the scales.

-
-

display

-

boolean

-

false

-

No

-

Whether to display the axis.

-

color

-

<color>

-

#c0c0c0

-

No

-

Axis color.

-
- -**Table 4** ChartSeries - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

lineStyle

-

ChartLineStyle

-

-

-

No

-

Line style, such as the line width and whether the line is smooth.

-

headPoint

-

PointStyle

-

-

-

No

-

Style and size of the white point at the start of the line.

-

topPoint

-

PointStyle

-

-

-

No

-

Style and size of the top point.

-

bottomPoint

-

PointStyle

-

-

-

No

-

Style and size of the bottom point.

-

loop

-

ChartLoop

-

-

-

No

-

Whether to start drawing again when the screen is looped.

-
- -**Table 5** ChartLineStyle - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

width

-

<length>

-

1px

-

No

-

Line width.

-

smooth

-

boolean

-

false

-

No

-

Whether the line is smooth.

-
- -**Table 6** PointStyle - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

shape

-

string

-

circle

-

No

-

Shape of the highlight point. Available values are as follows:

-
  • Circle
  • Square
  • Triangle
-

size

-

<length>

-

5px

-

No

-

Size of the highlight point.

-

strokeWidth

-

<length>

-

1px

-

No

-

Stroke width.

-

strokeColor

-

<color>

-

#ff0000

-

No

-

Frame color.

-

fillColor

-

<color>

-

#ff0000

-

No

-

Fill color.

-
- -**Table 7** ChartLoop +## Required Permissions - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

margin

-

<length>

-

1

-

No

-

Number of erased points (horizontal distance between the latest drawn point and the earliest point). You are not advised to use margin together with topPoint, bottomPoint, or headPoint for lite devices. If you do so, there is a possibility that the point is in the erase area and invisible.

-

gradient

-

boolean

-

false

-

No

-

Whether to perform gradient erase.

-
- -**Table 8** Point5+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

value

-

number

-

0

-

Yes

-

Y coordinate of the point to draw.

-

pointStyle

-

PointStyle

-

-

-

No

-

Style of the point.

-

description

-

string

-

-

-

No

-

Description text of the point.

-

textLocation

-

string

-

-

-

No

-

Description text position relative to the point. Available values are as follows:

-

top: above the point

-

bottom: below the point

-

none: not displayed

-

textColor

-

<color>

-

#000000

-

No

-

Color of the description text.

-

lineDash

-

string

-

solid

-

No

-

Dashed line pattern. You can set the dash length and space length between the dashes. For example, "dashed, 5, 5" indicates a dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value "solid" indicates a solid line.

-

lineColor

-

<color>

-

#000000

-

No

-

Line color. If this attribute is not set, the strokeColor is used by default.

-
- -**Table 9** DataSegment5+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

startColor

-

Color

-

-

-

No

-

Color of the start position. If this attribute is set, endColor must be set. If this attribute is not set, the default color array preset in the system is used. For details about the color values, see the next table.

-

endColor

-

Color

-

-

-

No

-

Color of the end position. If this attribute is set, startColor must be set.

-

If this attribute is not set, the default color array preset in the system is used.

-

value

-

number

-

0

-

Yes

-

Percentage for the current data segment. The maximum value is 100.

-

name

-

string

-

-

-

No

-

Name of this data segment.

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Data Segment

-

Light Mode

-

Dark Mode

-

0

-

Start color: #f7ce00; end color: #f99b11

-

Start color: #d1a738; end color: #eb933d

-

1

-

Start color: #f76223; end color: #f2400a

-

Start color: #e67d50; end color: #d9542b

-

2

-

Start color: #f772ac; end color: #e65392

-

Start color: #d5749e; end color: #d6568d

-

3

-

Start color: #a575eb; end color: #a12df7

-

Start color: #9973d1; end color: #5552d9

-

4

-

Start color: #7b79f7; end color: #4b48f7

-

Start color: #7977d9; end color: #f99b11

-

5

-

Start color: #4b8af3; end color: #007dff

-

Start color: #4c81d9; end color: #217bd9

-

6

-

Start color: #73c1e6; end color: #4fb4e3

-

Start color: #5ea6d1; end color: #4895c2

-

7

-

Start color: #a5d61d; end color: #69d14f

-

Start color: #91c23a; end color: #70ba5d

-

8

-

Start color: #a2a2b0; end color: #8e8e93

-

Start color: #8c8c99; end color: #6b6b76

-
- -For gauge charts, the following attribute is supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

percent

-

number

-

0

-

No

-

Percentage of the current value to the total value. The value ranges from 0 to 100.

-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

stroke-width

-

<length>

-

32px (gauge charts)

-

24px (rainbow charts)

-

No

-

Width of the scale bar for gaugeand rainbow charts.

-

start-angle

-

<deg>

-

240 (gauge charts)

-

0 (rainbow charts)

-

No

-

Start angle of the scale bar for gauge and rainbow charts, which starts from the direction of zero o'clock. The value ranges from 0 to 360.

-

total-angle

-

<deg>

-

240 (gauge charts)

-

360 (rainbow charts)

-

No

-

Total length of the scale bar for gauge and rainbow charts. The value ranges from –360 to 360. A negative number indicates the anticlockwise direction.

-

center-x

-

<length>

-

-

-

No

-

Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the position style in the common styles, and must be used together with center-y and radius. This style is supported by the gauge chart only.

-

center-y

-

<length>

-

-

-

No

-

Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the position style in the common styles, and must be used together with center-x and radius. This style is supported by the gauge chart only.

-

radius

-

<length>

-

-

-

No

-

Radius of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the width and height in the common styles, and must be used together with center-x and center-y. This style is supported by the gauge chart only.

-

colors

-

Array

-

-

-

No

-

Color of each section for the scale bar of the gauge component.

-

For example, colors: #ff0000, #00ff00. This style is supported by the gauge chart only.

-

weights

-

Array

-

-

-

No

-

Weight of each section for the scale bar of the gauge component.

-

For example, weights: 2, 2. This style is supported by the gauge chart only.

-

font-family5+

-

Array

-

-

-

No

-

Font style of the description text. You can use Custom Font Styles.

-

font-size5+

-

<length>

-

-

-

No

-

Font size of the description text.

-
- -## Events - -Events in [Universal Events](js-components-common-events.md) are supported. - -## Methods - -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. - - - - - - - - - - - - -

Method

-

Parameter

-

Description

-

append

-

{

-

serial: number, // Set the data subscript of the line chart to be updated.

-

data: Array<number>, // Set the new data.

-

}

-

Data is dynamically added to an existing data sequence. The target sequence is specified based on serial, which is the subscript of the datasets array and starts from 0. datasets[index].data is not updated. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the xAxis min/max setting.

-
- -## Example Code - -1. Line chart - - ``` - -
- - - - - -
- ``` +None - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - .chart-region { - height: 400px; - width: 700px; - } - .chart-background { - object-fit: fill; - } - .chart-data { - width: 700px; - height: 600px; - } - button { - width: 100%; - height: 50px; - background-color: #F4F2F1; - text-color: #0C81F3; - } - ``` - ``` - // xxx.js - export default { - data: { - lineData: [ - { - strokeColor: '#0081ff', - fillColor: '#cce5ff', - data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], - gradient: true, - } - ], - lineOps: { - xAxis: { - min: 0, - max: 20, - display: false, - }, - yAxis: { - min: 0, - max: 1000, - display: false, - }, - series: { - lineStyle: { - width: "5px", - smooth: true, - }, - headPoint: { - shape: "circle", - size: 20, - strokeWidth: 5, - fillColor: '#ffffff', - strokeColor: '#007aff', - display: true, - }, - loop: { - margin: 2, - gradient: true, - } - } - }, - }, - addData() { - this.$refs.linechart.append({ - serial: 0, - data: [Math.floor(Math.random() * 400) + 400] - }) - } - } - ``` +## Child Components - ![](figures/en-us_image_0000001173324843.png) +Not supported -2. Bar chart - ``` - -
- - - - -
- ``` +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------------------ | ---------------------------------------- | ---- | ---- | ---------------------------------------- | +| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:
- **bar**: bar chart.
- **line**: line chart.
- **gauge**: gauge chart.
- **progress**5+: circle chart of progresses.
- **loading**5+: circle chart of loading processes.
- **rainbow**5+: circle chart of proportions.| +| options | ChartOptions | - | No | Chart parameters. You must set parameters for bar charts and line charts. Parameter settings for gauge charts do not take effect. You can set the minimum value, maximum value, scale, and line width of the x-axis or y-axis, whether to display the x-axis and y-axis, and whether the line is smooth. Dynamic modification is not supported.| +| datasets | Array<ChartDataset> | - | No | Data sets. You must set data sets for bar charts and line charts. Data sets for a gauge chart do not take effect. You can set multiple datasets and their background colors.| +| segments5+ | DataSegment \| Array<DataSegment> | - | No | Data structures used by **progress**, **loading**, and **rainbow** charts.
**DataSegment** is available for **progress** and **loading** charts.
**Array<DataSegment>** is available for **rainbow** charts. A maximum of nine **DataSegment**s are supported in the array.| +| effects5+ | boolean | true | No | Whether to enable the effects for **progress** and **rainbow** charts. | +| animationduration6+ | number | 3000 | No | Animation duration for expanding a **rainbow** chart, in milliseconds. | + +**Table 1** ChartOptions + +| Name | Type | Default Value | Mandatory | Description | +| ------ | ----------- | ---- | ---- | ---------------------------------------- | +| xAxis | ChartAxis | - | Yes | X-axis parameters. You can set the minimum value, maximum value, and scale of the x-axis, and whether to display the x-axis. | +| yAxis | ChartAxis | - | Yes | Y-axis parameters. You can set the minimum value, maximum value, and scale of the y-axis, and whether to display the y-axis. | +| series | ChartSeries | - | No | Data sequence parameters. Only line charts support this attribute.
- Line style, such as the line width and whether the line is smooth.
- Style and size of the white point at the start of the line.| - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - .data-region { - height: 400px; - width: 700px; - } - .data-background { - object-fit: fill; - } - .data-bar { - width: 700px; - height: 400px; - } - ``` +**Table 2** ChartDataset - ``` - // xxx.js - export default { - data: { - barData: [ - { - fillColor: '#f07826', - data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628], - }, - { - fillColor: '#cce5ff', - data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410], - }, - { - fillColor: '#ff88bb', - data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657], - }, - ], - barOps: { - xAxis: { - min: 0, - max: 20, - display: false, - axisTick: 10, - }, - yAxis: { - min: 0, - max: 1000, - display: false, - }, - }, - } - } - ``` +| Name | Type | Default Value | Mandatory | Description | +| ----------- | ---------------------------------------- | -------- | ---- | ---------------------- | +| strokeColor | <color> | \#ff6384 | No | Stroke color. Only line charts support this attribute. | +| fillColor | <color> | \#ff6384 | No | Fill color.
For line charts, the value indicates the gradient color to fill.| +| data | Array<number> \| Array<Point>5+ | - | Yes | Data of the drawn line or bar. | +| gradient | boolean | false | No | Whether to display the gradient color. Only line charts support this attribute. | + +**Table 3** ChartAxis + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------------- | -------- | ---- | ---------------------------------------- | +| min | number | 0 | No | Minimum value of the axis. Only line charts support negative numbers. | +| max | number | 100 | No | Maximum value of the axis. Only line charts support negative numbers. | +| axisTick | number | 10 | No | Number of scales displayed on the axis. The value ranges from 1 to 20. The display effect depends on the calculation result of Number of pixels occupied by the image width/(**max** – **min**).
In the bar chart, the number of bars in each group of data is the same as the number of scales, and the bars are displayed at the scales.| +| display | boolean | false | No | Whether to display the axis. | +| color | <color> | \#c0c0c0 | No | Axis color. | - ![](figures/en-us_image_0000001173164929.png) +**Table 4** ChartSeries -3. Gauge chart +| Name | Type | Default Value | Mandatory | Description | +| ----------- | -------------- | ---- | ---- | -------------------- | +| lineStyle | ChartLineStyle | - | No | Line style, such as the line width and whether the line is smooth. | +| headPoint | PointStyle | - | No | Style and size of the white point at the start of the line. | +| topPoint | PointStyle | - | No | Style and size of the top point. | +| bottomPoint | PointStyle | - | No | Style and size of the bottom point. | +| loop | ChartLoop | - | No | Whether to start drawing again when the screen is looped.| - ``` - -
-
- -
-
- ``` +**Table 5** ChartLineStyle - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - .gauge-region { - height: 400px; - width: 400px; - } - .data-gauge { - colors: #83f115, #fd3636, #3bf8ff; - weights: 4, 2, 1; - } - ``` +| Name | Type | Default Value | Mandatory | Description | +| ------ | -------------- | ----- | ---- | ----- | +| width | <length> | 1px | No | Line width.| +| smooth | boolean | false | No | Whether the line is smooth.| - ![](figures/en-us_image_0000001127125264.png) +**Table 6** PointStyle +| Name | Type | Default Value | Mandatory | Description | +| ----------- | -------------- | -------- | ---- | ---------------------------------------- | +| shape | string | circle | No | Shape of the highlight point. Available values are as follows:
- circle
- square
- triangle| +| size | <length> | 5px | No | Size of the highlight point. | +| strokeWidth | <length> | 1px | No | Stroke width. | +| strokeColor | <color> | \#ff0000 | No | Stroke color. | +| fillColor | <color> | \#ff0000 | No | Fill color. | + +**Table 7** ChartLoop + +| Name | Type | Default Value | Mandatory | Description | +| -------- | -------------- | ----- | ---- | ---------------------------------------- | +| margin | <length> | 1 | No | Number of erased points (horizontal distance between the latest drawn point and the earliest point). You are not advised to use **margin** together with **topPoint**, **bottomPoint**, or **headPoint** for mini-, small- and standard-system devices. If you do so, there is a possibility that the point is in the erase area and invisible.| +| gradient | boolean | false | No | Whether to perform gradient erase. | + +**Table 8** Point5+ + +| Name | Type | Default Value | Mandatory | Description | +| ------------ | ------------- | -------- | ---- | ---------------------------------------- | +| value | number | 0 | Yes | Y coordinate of the point to draw. | +| pointStyle | PointStyle | - | No | Style of the point. | +| description | string | - | No | Description text of the point. | +| textLocation | string | - | No | Position of the description text relative to the point. Available values are as follows: **top**: above the point
**bottom**: below the point
**none**: not displayed| +| textColor | <color> | \#000000 | No | Color of the description text. | +| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. For example, **"dashed, 5, 5"** indicates a dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.| +| lineColor | <color> | \#000000 | No | Line color. If this attribute is not set, the value of **strokeColor** is used. | + +**Table 9** DataSegment5+ + +| Name | Type | Default Value | Mandatory | Description | +| ---------- | ------ | ---- | ---- | ---------------------------------------- | +| startColor | Color | - | No | Color of the start position. If this attribute is set, **endColor** must be set. If this attribute is not set, the default color array preset in the system is used. For details about the color values, see the next table.| +| endColor | Color | - | No | Color of the end position. If this attribute is set, **startColor** must be set.
If this attribute is not set, the default color array preset in the system is used.| +| value | number | 0 | Yes | Percentage for the data segment. The maximum value is **100**. | +| name | string | - | No | Name of the data segment. | + +| Data Segment | Light Mode | Dark Mode | +| ---- | --------------------------- | --------------------------- | +| 0 | Start color: \#f7ce00; end color: \#f99b11| Start color: \#d1a738; end color: \#eb933d| +| 1 | Start color: \#f76223; end color: \#f2400a| Start color: \#e67d50; end color: \#d9542b| +| 2 | Start color: \#f772ac; end color: \#e65392| Start color: \#d5749e; end color: \#d6568d| +| 3 | Start color: \#a575eb; end color: \#a12df7| Start color: \#9973d1; end color: \#5552d9| +| 4 | Start color: \#7b79f7; end color: \#4b48f7| Start color: \#7977d9; end color: \#f99b11| +| 5 | Start color: \#4b8af3; end color: \#007dff| Start color: \#4c81d9; end color: \#217bd9| +| 6 | Start color: \#73c1e6; end color: \#4fb4e3| Start color: \#5ea6d1; end color: \#4895c2| +| 7 | Start color: \#a5d61d; end color: \#69d14f| Start color: \#91c23a; end color: \#70ba5d| +| 8 | Start color: \#a2a2b0; end color: \#8e8e93| Start color: \#8c8c99; end color: \#6b6b76| + +For the **gauge** charts, the following attributes are also supported. + +| Name | Type | Default Value | Mandatory | Description | +| ------- | ------ | ---- | ---- | ---------------------- | +| percent | number | 0 | No | Percentage of the current value to the total value. The value ranges from 0 to 100.| + + +## Styles + + + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------------ | -------------- | -------------------------- | ---- | ---------------------------------------- | +| stroke-width | <length> | 32px (**gauge** charts)
24px (**rainbow** charts)| No | Width of the scale bar for **gauge** and **rainbow** charts. | +| start-angle | <deg> | 240 (**gauge** charts)
0 (**rainbow** charts) | No | Start angle of the scale bar for **gauge** and **rainbow** charts, which starts from zero o'clock. The value ranges from 0 to 360. | +| total-angle | <deg> | 240 (**gauge** charts)
360 (**rainbow** charts) | No | Total length of the scale bar for **gauge** and **rainbow** charts. The value ranges from –360 to 360. A negative number indicates the anticlockwise direction.| +| center-x | <length> | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-y** and **radius**. This style is supported by the gauge chart only.| +| center-y | <length> | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-x** and **radius**. This style is supported by the gauge chart only.| +| radius | <length> | - | No | Radius of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **width** and **height** in the common styles, and must be used together with **center-x** and **center-y**. This style is supported by the gauge chart only.| +| colors | Array | - | No | Color of each section for the scale bar of the gauge component.
For example, **colors: \#ff0000, #00ff00**. This style is supported by the gauge chart only.| +| weights | Array | - | No | Weight of each section for the scale bar of the gauge component.
For example, **weights: 2, 2**. This style is supported by the gauge chart only.| +| font-family5+ | Array | - | No | Font style of the description text. You can use a [custom font](../arkui-js/js-components-common-customizing-font.md).| +| font-size5+ | <length> | - | No | Font size of the description text. | + + +## Events + +The [universal events](../arkui-js/js-components-common-events.md) are supported. + + +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| append | {
serial: number, // Set the data subscript of the line chart to be updated.
data: Array<number>, // Set the new data.
} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. **datasets[index].data** is not updated. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.| + +## Example + +1. Line chart + ```html + +
+ + + + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + .chart-region { + height: 400px; + width: 700px; + } + .chart-background { + object-fit: fill; + } + .chart-data { + width: 700px; + height: 600px; + } + button { + width: 100%; + height: 50px; + background-color: #F4F2F1; + text-color: #0C81F3; + } + ``` + + ```js + // xxx.js + export default { + data: { + lineData: [ + { + strokeColor: '#0081ff', + fillColor: '#cce5ff', + data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], + gradient: true, + } + ], + lineOps: { + xAxis: { + min: 0, + max: 20, + display: false, + }, + yAxis: { + min: 0, + max: 1000, + display: false, + }, + series: { + lineStyle: { + width: "5px", + smooth: true, + }, + headPoint: { + shape: "circle", + size: 20, + strokeWidth: 5, + fillColor: '#ffffff', + strokeColor: '#007aff', + display: true, + }, + loop: { + margin: 2, + gradient: true, + } + } + }, + }, + addData() { + this.$refs.linechart.append({ + serial: 0, + data: [Math.floor(Math.random() * 400) + 400] + }) + } + } + ``` + + ![en-us_image_0000001173324843](figures/en-us_image_0000001173324843.png) + +2. Bar chart + ```html + +
+ + + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + .data-region { + height: 400px; + width: 700px; + } + .data-background { + object-fit: fill; + } + .data-bar { + width: 700px; + height: 400px; + } + ``` + + ```js + // xxx.js + export default { + data: { + barData: [ + { + fillColor: '#f07826', + data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628], + }, + { + fillColor: '#cce5ff', + data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410], + }, + { + fillColor: '#ff88bb', + data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657], + }, + ], + barOps: { + xAxis: { + min: 0, + max: 20, + display: false, + axisTick: 10, + }, + yAxis: { + min: 0, + max: 1000, + display: false, + }, + }, + } + } + ``` + + ![en-us_image_0000001173164929](figures/en-us_image_0000001173164929.png) + +3. Gauge chart + ```html + +
+
+ +
+
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + .gauge-region { + height: 400px; + width: 400px; + } + .data-gauge { + colors: #83f115, #fd3636, #3bf8ff; + weights: 4, 2, 1; + } + ``` + + ![en-us_image_0000001127125264](figures/en-us_image_0000001127125264.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-divider.md b/en/application-dev/reference/arkui-js/js-components-basic-divider.md index c8bb190dbaeacebddbc1325c9ef0ff41b96124d5..ab4bd1cb294cb6e492df235a87b63252d146b6e7 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-divider.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-divider.md @@ -1,214 +1,66 @@ -# divider +# divider -The **** component is used to separate content blocks and content elements. It can be used for the list or UI layout. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component is used to separate content blocks and content elements. It can be used for the list or UI layout. + +## Required Permissions None -## Child Components + +## Child Components Not supported -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

vertical

-

boolean

-

false

-

No

-

Whether to use the vertical divider. The default value is false, indicating that the horizontal divider is used.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The **focusable** and **disabled** attributes are not supported. - -## Styles - -Only the following style attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

margin

-

<length>

-

0

-

No

-

Shorthand attribute to set all margins in a declaration. You can set 1 to 4 values.

-

margin-[left|top|right|bottom]

-

<length>

-

0

-

No

-

Shorthand attribute of the length type to set left, top, right, and bottom margins attributes. Its unit is px and default value is 0.

-

color

-

<color>

-

#08000000

-

No

-

Color of the divider.

-

stroke-width

-

<length>

-

1

-

No

-

Width of the divider.

-

display

-

string

-

flex

-

No

-

Type of the bounding box generated by the divider. The value can be flex or none. The default value is flex.

-

visibility

-

string

-

visible

-

No

-

Whether to display the divider. Invisible dividers also occupy space. visible indicates that the divider is displayed, and hidden indicates that the divider is not displayed.

-

line-cap

-

string

-

butt

-

No

-

Cap style of the divider. The default value is butt. Available values are as follows:

-
  • butt: The ends of the divider are squared off.
  • round: A rounded cap is added to each end of the divider.
  • square: A square cap is added to each end of the divider.
-
NOTE:

If the value is round or square, the line length increases by the line width.

-
-

flex

-

number

-

-

-

No

-

How to divide available space of the parent component for each child component. This is a shorthand attribute to set the flex-grow attribute.

-
NOTE:

This attribute takes effect only when the parent component is <div>, <list-item>, or <tabs>.

-
-

flex-grow

-

number

-

0

-

No

-

How much a child component will grow. The value specifies allocation of the remaining space on the main axis of the parent component. Size of available space = Container size - Total size of all child components. Value 0 indicates that the child component does not grow.

-
NOTE:

This attribute takes effect only when the parent component is <div>, <list-item>, or <tabs>.

-
-

-

flex-shrink

-

number

-

1

-

No

-

How much a child component will shrink. The shrink occurs only when the sum of default element widths is greater than that of the parent component. Value 0 indicates that the child component does not shrink.

-
NOTE:

This attribute takes effect only when the parent component is <div>, <list-item>, or <tabs>.

-
-

flex-basis

-

<length>

-

-

-

-

No

-

Initial length of a child component on the main axis

-
NOTE:

This attribute takes effect only when the parent component is <div>, <list-item>, or <tabs>.

-
-
- -## Events + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------- | ----- | ---- | -------------------- | +| vertical | boolean | false | No | Whether to use the vertical divider. The default value is **false**, indicating that the horizontal divider is used.| + +> **NOTE** +> +> The **focusable** and **disabled** attributes are not supported. + + +## Styles + +Only the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| --------------------------------- | -------------- | ---------- | ---- | ---------------------------------------- | +| margin | <length> | 0 | No | Shorthand attribute to set the margin for all sides in a declaration. The attribute can have one to four values: | +| margin-[left\|top\|right\|bottom] | <length> | 0 | No | Shorthand attribute of the length type to set left, top, right, and bottom margins attributes. Its unit is px and default value is **0**.| +| color | <color> | \#08000000 | No | Color of the divider. | +| stroke-width | <length> | 1 | No | Width of the divider. | +| display | string | flex | No | Type of the bounding box generated by the divider. The value can be **flex** or **none**. The default value is **flex**. | +| visibility | string | visible | No | Whether to display the divider. Invisible dividers also occupy space. **visible** indicates that the divider is displayed, and **hidden** indicates that the divider is not displayed.| +| line-cap | string | butt | No | Cap style of the divider. The default value is **butt**. Available values are as follows:
- **butt**: The ends of the divider are squared off.
- **round**: A rounded cap is added to each end of the divider. The divider length will increase by the stroke width.
- **square**: A square cap is added to each end of the divider. The divider length will increase by the stroke width.| +| flex | number | - | No | How to divide available space of the parent component for each child component. This is a shorthand attribute to set the **flex-grow** attribute.
This attribute takes effect only when the parent component is **\
**, **\**, or **\**.| +| flex-grow | number | 0 | No | How much a child component will grow. The value specifies allocation of the available space on the main axis of the parent component. Size of available space = Container size - Total size of all child components. Value **0** indicates that the child component does not grow.
This attribute takes effect only when the parent component is **\
**, **\**, or **\**.| +| flex-shrink | number | 1 | No | How much a child component will shrink. The shrink occurs only when the sum of default element widths is greater than that of the parent component. Value **0** indicates that the child component does not shrink.
This attribute takes effect only when the parent component is **\
**, **\**, or **\**.| +| flex-basis | <length> | - | No | Initial length of a child component on the main axis.
This attribute takes effect only when the parent component is **\
**, **\**, or **\**.| + + +## Events Not supported -## Methods + +## Methods Not supported -## Example -``` +## Example + +```html
@@ -217,7 +69,7 @@ Not supported
``` -``` +```css /* xxx.css */ .container { margin: 20px; @@ -242,5 +94,4 @@ Not supported } ``` -![](figures/1-1.jpg) - +![1-1](figures/1-1.jpg) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md b/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md index 8dfd02bd6d6090751ae8b212c8762b9deda2a046..f5fee8be990a3a49e8012f05e7a9129b5860bcf5 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md @@ -1,299 +1,76 @@ -# image-animator +# image-animator -The **** component is used to provide an image frame animator. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Child Component +The **\** component is used to provide an image frame animator. + + +## Child Components Not supported -## Attributes -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +## Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

images

-

Array<ImageFrame>

-

-

-

Yes

-

Image frame information. The frame information includes the image path, size, and location. Currently, the following image formats are supported: PNG and JPG. For details about ImageFrame, see Table 1.

-
NOTE:

Set this attribute using data binding, for example, images = {{images}}. Declare the corresponding variable images: [{src: "/common/heart-rate01.png"}, {src: "/common/heart-rate02.png"}] in the JavaScript.

-

Declare the variable images: [{src: "/common/heart-rate01.png", duration: "100"}, {src: "/common/heart-rate02.png", duration: "200"}] in the JavaScript. You can set the duration (in milliseconds) of each image frame. 6+

-
-

predecode6+

-

number

-

0

-

No

-

Whether to enable pre-decoding. The default value is 0, indicating that pre-decoding is disabled. If this parameter is set to 2, the last two images are loaded to the cache in advance to improve the performance when the current page is played.

-

iteration

-

number | string

-

infinite

-

No

-

Number of times that the frame animation is played. number indicates a fixed number of playback operations, and infinite indicates an unlimited number of playback operations.

-

reverse

-

boolean

-

false

-

No

-

Playback sequence. The value false indicates that images are played from the first one to the last one, and true indicates that images are played from the last one to the first one.

-

fixedsize

-

boolean

-

true

-

No

-

Whether the image size is fixed to the widget size. true: The image size is the same as the widget size. In this case, the width, height, top, and left attributes of the image are invalid. false: The width, height, top, and left attributes of each image must be set separately.

-

duration

-

string

-

-

-

Yes

-

Single video playback duration. The unit can be s (standing for seconds) or ms. The default unit is ms. If the value is 0, no image is played. The value change takes effect only at the start of the next cycle. If image-specific durations have been set, the settings of this attribute do not take effect.

-

fillmode5+

-

string

-

forwards

-

No

-

Status of the frame animation after its playback is complete. Available values are as follows:

-
  • none: Restores to the initial status.
  • forwards: Retains the ending status defined for the last key frame.
-
+In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -**Table 1** ImageFrame description +| Name | Type | Default Value | Mandatory | Description | +| ---------------------- | -------------------------- | -------- | ---- | ---------------------------------------- | +| images | Array<ImageFrame> | - | Yes | Image frame information. The frame information includes the image path, size, and location. The supported image formats include PNG and JPG.
Set this attribute using data binding.
- Reference image resources in the HML file: **images = {{images}}**.
- Declare the corresponding variables in the JS file:
**images: [{src: "/common/heart-rate01.png",duration:"100"}]** Since API version 6,the duration (in milliseconds) per image frame can be set.| +| predecode6+ | number | 0 | No | Whether to enable pre-decoding. The default value **0** indicates that pre-decoding is disabled. The value **2** indicates that two images following the currently playing frame will be cached in advance to improve performance.| +| iteration | number \| string | infinite | No | Number of times that the frame animation is played. **number** indicates a fixed number of playback operations, and **infinite** indicates an unlimited number of playback operations.| +| reverse | boolean | false | No | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.| +| fixedsize | boolean | true | No | Whether the image size is the same as the component size.
**true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid. **false**: The width, height, top, and left attributes of each image must be set separately.| +| duration | string | - | Yes | Single video playback duration. The unit can be s (standing for seconds) or ms. The default unit is ms. If the value is **0**, no image is played. The value change takes effect only at the start of the next cycle. If image-specific durations have been set, the settings of this attribute do not take effect. | +| fillmode5+ | string | forwards | No | Status of the frame animation after its playback is complete. Available values are as follows:
- **none**: Restores to the initial status.
- **forwards**: Retains the ending status defined for the last key frame.| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

src

-

<uri>

-

-

-

Yes

-

Image path. The image format can be SVG, PNG, or JPG.

-

width

-

<length>

-

0

-

No

-

Image width

-

height

-

<length>

-

0

-

No

-

Image height

-

top

-

<length>

-

0

-

No

-

Vertical coordinate of the image relative to the upper left corner of the widget

-

left

-

<length>

-

0

-

No

-

Horizontal coordinate of the image relative to the upper left corner of the widget

-

duration6+

-

number

-

-

-

No

-

Playback duration of each image frame, in milliseconds.

-
+**Table 1** ImageFrame -## Styles +| Name | Type | Default Value | Mandatory | Description | +| --------------------- | -------------- | ---- | ---- | ---------------------- | +| src | <uri> | - | Yes | Image path. The image format can be SVG, PNG, or JPG.| +| width | <length> | 0 | No | Image width. | +| height | <length> | 0 | No | Image height. | +| top | <length> | 0 | No | Vertical coordinate of the image relative to the upper left corner of the component. | +| left | <length> | 0 | No | Horizontal coordinate of the image relative to the upper left corner of the component. | +| duration6+ | number | - | No | Playback duration of each image frame, in milliseconds. | -Styles in [Universal Styles](js-components-common-styles.md) are supported. -## Events +## Styles -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. +The [universal styles](../arkui-js/js-components-common-styles.md) are supported. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

start

-

-

-

Triggered when the frame animation starts

-

pause

-

-

-

Triggered when the frame animation pauses

-

stop

-

-

-

Triggered when the frame animation stops

-

resume

-

-

-

Triggered when the frame animation resumes

-
-## Methods +## Events -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

start

-

-

-

Starts to play the frame animation of an image. If this method is called again, the playback starts from the first frame.

-

pause

-

-

-

Pauses the frame animation playback of an image.

-

stop

-

-

-

Stops the frame animation playback of an image.

-

resume

-

-

-

Resumes the frame animation playback of an image.

-

getState

-

-

-

Obtains the playback state. Available values are as follows:

-
  • Playing
  • Paused
  • Stopped
-
+| Name | Parameter | Description | +| ------ | ---- | --------- | +| start | - | Triggered when the frame animation starts.| +| pause | - | Triggered when the frame animation pauses.| +| stop | - | Triggered when the frame animation stops.| +| resume | - | Triggered when the frame animation resumes.| -## Example Code -``` +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| -------- | ---- | ---------------------------------------- | +| start | - | Starts to play the frame animation of an image. If this method is called again, the playback starts from the first frame. | +| pause | - | Pauses the frame animation playback of an image. | +| stop | - | Stops the frame animation playback of an image. | +| resume | - | Resumes the frame animation playback of an image. | +| getState | - | Obtains the playback state. Available values are as follows:
- playing
- paused
- stopped| + + +## Example + +```html
@@ -306,7 +83,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -335,7 +112,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods. } ``` -``` +```js //xxx.js export default { data: { @@ -414,5 +191,4 @@ export default { }; ``` -![](figures/image-animator.gif) - +![image-animator](figures/image-animator.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-image.md b/en/application-dev/reference/arkui-js/js-components-basic-image.md index 2afd0a80fce71b2d7cbc3b8f756e57e3eb8ce303..53b335e34c30317f99f789bd22358bad5d8ad279 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-image.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-image.md @@ -1,223 +1,94 @@ -# image +# image -The **** component is used to render and display images. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Child Component +The **\** component is used to render and display images. + + +## Child Components Not supported -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

src

-

string

-

-

-

No

-

Image path, which supports local paths. The supported image formats include PNG, JPG, BMP, SVG, and GIF.

-

Base64 string6+ is supported. The format is data:image/[png | jpeg | bmp | webp];base64, [base64 data],, where [base64 data] is a Base64 string.

-

The path prefix of dataability:// is supported, which allows access to the image path provided by the Data ability.

-

alt

-

string

-

-

-

No

-

Placeholder image displayed during image loading.

-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following style attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

object-fit

-

string

-

cover

-

No

-

Image scale type. For details about available values, see Types of the object-fit style. The SVG format is not supported.

-

match-text-direction

-

boolean

-

false

-

No

-

Whether image orientation changes with the text direction. The SVG format is not supported.

-

fit-original-size

-

boolean

-

false

-

No

-

Whether the <image> component adapts to the image source size when the width and height are not set. If this attribute is set to true, the object-fit attribute does not take effect. SVG images do not support this attribute.

-

object-position7+

-

string

-

0px 0px

-

No

-

Position of an image in the component.

-

There are two setting types:

-

1. Pixels. For example, 15px 15px indicates the moving position along the x-axis or y-axis.

-

2. Characters. Optional values are as follows:

-
  • left: The image is displayed on the left of the component.
  • top The image is displayed on the top of the component.
  • right The image is displayed on the right of the component.
  • bottom The image is displayed at the bottom of the component.
-
- -**Table 1** Types of the object-fit style - - - - - - - - - - - - - - - - - - - - - - -

Type

-

Description

-

cover

-

The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries and displayed in the middle.

-

contain

-

The image is scaled with the aspect ratio retained for the image to be completely displayed within the display boundaries and displayed in the middle.

-

fill

-

The image is resized to fill the display area and its aspect ratio is not retained.

-

none

-

The image is displayed in the middle with its aspect ratio and size retained.

-

scale-down

-

The image is displayed in the middle with its aspect ratio retained. The size is equal to or smaller than the original size.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->When using an SVG image, note that: ->- The SVG image will not be drawn if the length or width of the **** component is infinity. ->- If the image length and width are not specified in the SVG description, the SVG fills the **** component area. ->- If the image length and width are specified in the SVG description, the following rules are adopted to decide the final display effect: ->1. If the **** component is too small to afford the SVG image, the SVG image is cropped and only its upper left part is displayed in the component. ->2. If the **** component is big enough to afford the SVG image, this SVG image is displayed in the upper left corner of the component. - -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

complete(Rich)

-

{ width: width, height: height }

-

Triggered when an image is successfully loaded. The loaded image is returned.

-

error(Rich)

-

{ width: width, height: height }

-

Triggered when an exception occurs during image loading. In this case, the width and height are 0.

-
- -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example Code -``` +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| src | string | - | No | Image path, which supports local paths. The supported image formats include PNG, JPG, BMP, SVG, and GIF.
- The Base64 string6+ is supported in the following format: data:image/[png \| jpeg \| bmp \| webp];base64, [base64 data], where **[base64 data]** is a Base64 string.
- The path prefix of **dataability://** is supported, which allows access to the image path provided by the Data ability.6+| +| alt | string | - | No | Alternative information for the image, which is displayed during image loading. | + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---------------------------- | ------- | ------------ | ---- | ---------------------------------------- | +| object-fit | string | cover | No | Image scale type. This style is not supported for SVG images. For details about available values, see **object-fit**.| +| match-text-direction | boolean | false | No | Whether image orientation changes with the text direction. This style is not supported for SVG images. | +| fit-original-size | boolean | false | No | Whether the **\** component adapts to the image source size when its width and height are not set. If this style is set to **true**, **object-fit** will not take effect. This style is not supported for SVG images.| +| object-position7+ | string | 0px 0px | No | Position of an image in the component.
The options are as follows:
1. Pixels. For example, **15px 15px** indicates the moving position along the x-axis or y-axis.
2. Characters. Optional values are as follows:
- **left**: The image is displayed on the left of the component.
- **top** The image is displayed on the top of the component.
- **right** The image is displayed on the right of the component.
- **bottom** The image is displayed at the bottom of the component.| + +**Table 1** object-fit + +| Type | Description | +| ---------- | ------------------------------------ | +| cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries and displayed in the middle.| +| contain | The image is scaled with the aspect ratio retained for the image to be completely displayed within the display boundaries and displayed in the middle. | +| fill | The image is scaled to fill the display area, and its aspect ratio is not retained. | +| none | The image is displayed in the middle with its aspect ratio and size retained. | +| scale-down | The image is displayed in the middle with its aspect ratio retained. The size is equal to or smaller than the original size. | + +> **NOTE** +> +> When using an SVG image, note that: +> +> - The SVG image will not be drawn if the length or width of the **\** component is infinity. +> +> - If the image length and width are not specified in the SVG description, the SVG image fills the **\** component area. +> +> - If the image length and width are specified in the SVG description, the following rules are adopted to decide the final display effect: +> +> 1. If the **\** component is too small to afford the SVG image, the SVG image is cropped and only its upper left part is displayed in the component. +> +> 2. If the **\** component is big enough to afford the SVG image, this SVG image is displayed in the upper left corner of the component. + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +| Name | Parameter | Description | +| -------------- | ---------------------------------------- | ------------------------- | +| complete(Rich) | {
width: width,
height: height
} | Triggered when an image is successfully loaded. The loaded image size is returned.| +| error(Rich) | {
width: width,
height: height
} | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. | + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +```html
- + - +
``` -``` +```css /* xxx.css */ .container { justify-content: center; align-items: center; flex-direction: column; - - } .selects{ margin-top: 20px; @@ -227,7 +98,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -``` +```js // xxx.js export default { data: { @@ -240,5 +111,4 @@ export default { } ``` -![](figures/example.gif) - +![example](figures/example.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-label.md b/en/application-dev/reference/arkui-js/js-components-basic-label.md index 5e80973d014fa5c07630312c3ab44efbef7dfa00..3adcd954efec63b002f90f923cd8fe5b5dfdd500 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-label.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-label.md @@ -1,265 +1,67 @@ -# label +# label -The **** component defines labels for the ****, ****, and **** components. When a label is clicked, the click effect of the component associated with the label will be triggered. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\
-
- ``` - - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - } - .box{ - width: 200px; - height: 200px; - background-color: #ff0000; - margin-top: 30px; - } - .buttonBox{ - margin-top: 30px; - width: 250px; - justify-content: space-between; - } - button{ - background-color: #8e8b89; - color: white; - width: 100px; - height: 40px; - font-size: 24px; - } - ``` - - ``` - // xxx.js - import prompt from '@system.prompt'; - export default{ - data:{ - animation:'', - }, - onInit(){ - }, - onShow(){ - var options = { - duration: 1500, - easing: 'friction', - delay: 500, - fill: 'forwards', - iterations: 2, - direction: 'normal', - }; - var frames = [ - {transform: {translate: '-120px -0px'}, opacity: 0.1, offset: 0.0}, - {transform: {translate: '120px 0px'}, opacity: 1.0, offset: 1.0} - ]; - this.animation = this.$element('idName').animate(frames, options); - // handle finish event - this.animation.onfinish = function(){ - prompt.showToast({ - message: "The animation is finished." - }); - }; - // handle cancel event - this.animation.oncancel = function(){ - prompt.showToast({ - message: "The animation is canceled." - }); - }; - // handle repeat event - this.animation.onrepeat = function(){ - prompt.showToast({ - message: "The animation is repeated." - }); - }; - }, - start(){ - this.animation.play(); - }, - cancel(){ - this.animation.cancel(); - } - } - ``` - - ![](figures/animationapi-4.gif) - - -## getBoundingClientRect - -getBoundingClientRect\(\): [ ](#table1650917111414) +# Universal Methods + +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. + +After a component is assigned the **id** attribute, you can use the ID to obtain the component objects and call methods on them. + + +## animate + +animate( keyframes: Keyframes, options: Options): void + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | --------- | ---- | ------------------------------------ | +| keyframes | keyframes | Yes | Animation style. | +| options | Options | Yes | Array of objects used to set animation attributes. For details, see **Options**.| + + **Table 1** keyframes + +| Name | Type | Description | +| ------ | ------------------ | -------------------------------------- | +| frames | Array<Style> | Array of objects used to set animation attributes. For details, see **Style attributes**.| + + **Table 2** Style attributes + +| Name | Type | Default Value | Description | +| ------------------ | ---------------------------------------- | -------------------- | ---------------------------------------- | +| width | number | - | Width set for the component during playback of the animation. | +| height | number | - | Height set for the component during playback of the animation. | +| backgroundColor | <color> | none | Background color set for the component during playback of the animation. | +| opacity | number | 1 | Opacity set for the component. The value ranges from 0 to 1. | +| backgroundPosition | string | - | The value format is **x y**, in percentage or pixels.
The first value indicates the horizontal position, and the second value indicates the vertical position.
If only one value is specified, the other value is **50%**.| +| transformOrigin | string | 'center center' | Origin position of the transformed element.
The first value indicates the x-axis position. The value can be **left**, **center**, **right**, a length, or a percentage.
The second value indicates the y-axis position. The value can be **top**, **center**, **bottom**, a length, or a percentage.| +| transform | [Transform](../arkui-js/js-components-common-animation.md) | - | Transformation type set for a transformed element. | +| offset | number | - | - The value of **offset** must be within (0.0, 1.0] and sorted in ascending order if it is provided.
- If there are only two frames, **offset** can be left empty.
- If there are more than two frames, **offset** is mandatory.| + + **Table 3** Options + +| Name | Type | Default Value | Description | +| ---------------------- | -------------------------- | ------ | ---------------------------------------- | +| duration | number | 0 | Duration for playing the animation, in milliseconds. | +| easing | string | linear | Time curve of the animation. For details about the supported types, see **Available values of the easing attribute**. | +| delay | number | 0 | Delay for the animation start. The default value indicates no delay. | +| iterations | number \| string | 1 | Number of times the animation will be played. **number** indicates a fixed number of playback operations, and **Infinity** indicates an unlimited number of playback operations.| +| direction6+ | string | normal | Mode of playing the animation.
**normal**: Plays the animation in forward loop mode.
**reverse**: Plays the animation in reverse loop mode.
**alternate**: Plays the animation in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in backward direction.
**alternate-reverse**: plays the animation in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction.| +| fill | string | none | Start and end styles of the animation.
**none**: No style is applied to the target before or after the animation is executed.
**forwards**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed.
**backwards**6+: The animation uses the value defined in the first key frame during the **animation-delay**. When **animation-direction** is set to **normal** or **alternate**, the value in the **from** key frame is used. When **animation-direction** is set to **reverse** or **alternate-reverse**, the value in the **to** key frame is used.
**both**: The animation follows the **forwards** and **backwards** rules.| + + **Table 4** Available values of the easing attribute + +| Value | Description | +| ---------------------------------------- | ---------------------------------------- | +| linear | The animation speed keeps unchanged. | +| ease-in | The animation starts at a low speed. **cubic-bezier(0.42, 0.0, 1.0, 1.0)**.| +| ease-out | The animation ends at a low speed. **cubic-bezier(0.0, 0.0, 0.58, 1.0)**.| +| ease-in-out | The animation starts and ends at a low speed. **cubic-bezier(0.42, 0.0, 0.58, 1.0)**.| +| friction | The animation uses the damping curve, **cubic-bezier(0.2, 0.0, 0.2, 1.0)**.| +| extreme-deceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).| +| sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).| +| rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).| +| smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).| +| cubic-bezier(x1, y1, x2, y2) | You can customize an animation speed curve in the **cubic-bezier()** function. The x and y values of each input parameter must be between 0 and 1. | +| steps(number, step-position)6+ | The animation uses the step curve.
The **number** must be set and only an integer is supported.
**step-position** is optional. It can be set to **start** or **end**. The default value is **end**.| + +**Return value** + The **animation** attributes are as follows. + +| Name | Type | Description | +| --------- | ------- | ---------------------------------------- | +| finished | boolean | Read-only attribute, which indicates whether the animation playback is complete. | +| pending | boolean | Read-only attribute, which indicates whether the animation is waiting for the completion of other asynchronous operations (for example, start an animation with a delay).| +| playState | string | Read-write attribute, which indicates the playback status of the animation:
- **idle**: The animation is not running (playback ended or not started).
- **running**: The animation is running.
- **paused**: The animation is paused.
- **finished**: Animation playback ends.| +| startTime | number | Read-write attribute, which indicates the animation start time. This attribute is similar to **delay** in the **options** attribute. | + + The **animation** methods are as follows. + +| Method | Parameter | Description | +| ------- | ---- | ------- | +| play | - | Plays the animation.| +| finish | - | Ends the animation.| +| pause | - | Pauses the animation.| +| cancel | - | Cancels the animation.| +| reverse | - | Plays the animation in reverse.| + + The **animation** events are as follows. + +| Event | Description | +| ------------------ | -------- | +| start6+ | The animation starts. | +| cancel | The animation is forcibly canceled.| +| finish | The animation playback is complete. | +| repeat | The animation repeats. | + +**Example** +```html + +
+
+
+ + +
+
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; +} +.box{ + width: 200px; + height: 200px; + background-color: #ff0000; + margin-top: 30px; +} +.buttonBox{ + margin-top: 30px; + width: 250px; + justify-content: space-between; +} +button{ + background-color: #8e8b89; + color: white; + width: 100px; + height: 40px; + font-size: 24px; +} +``` + +```js +// xxx.js +import prompt from '@system.prompt'; +export default{ + data:{ + animation:'', + }, + onInit(){ + }, + onShow(){ + var options = { + duration: 1500, + easing: 'friction', + delay: 500, + fill: 'forwards', + iterations: 2, + direction: 'normal', + }; + var frames = [ + {transform: {translate: '-120px -0px'}, opacity: 0.1, offset: 0.0}, + {transform: {translate: '120px 0px'}, opacity: 1.0, offset: 1.0} + ]; + this.animation = this.$element('idName').animate(frames, options); + // handle finish event + this.animation.onfinish = function(){ + prompt.showToast({ + message: "The animation is finished." + }); + }; + // handle cancel event + this.animation.oncancel = function(){ + prompt.showToast({ + message: "The animation is canceled." + }); + }; + // handle repeat event + this.animation.onrepeat = function(){ + prompt.showToast({ + message: "The animation is repeated." + }); + }; + }, + start(){ + this.animation.play(); + }, + cancel(){ + this.animation.cancel(); + } +} +``` + +![animationapi-4](figures/animationapi-4.gif) + +## getBoundingClientRect + +getBoundingClientRect(): \ Obtains the size of the element and its position relative to the window. -- Return values - - **Table 5** Rect attributes6+ - - - - - - - - - - - - - - - - - - - - - - - - -

Attribute

-

Type

-

Description

-

width

-

number

-

Width of an element.

-

height

-

number

-

Height of an element.

-

left

-

number

-

Offset between the left boundary of the element and the window.

-

top

-

number

-

Offset between the upper boundary of the element and the window.

-
- -- Example - - ``` - // xxx.js - var rect = this.$element('id').getBoundingClientRect(); - console.info(`current element position is ${rect.left}, ${rect.top}`); - ``` - - -## createIntersectionObserver - -createIntersectionObserver\(param?: ObserverParam):Observer - -Gets notified of the visibility of an element on the current page. - -- Name - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

param

-

ObserverParam

-

-

-

Obtains the observer callback.

-
- - **Table 6** ObserverParam attributes6+ - - - - - - - - - - - - -

Attribute

-

Type

-

Description

-

ratios

-

Array<number>

-

When the component is out of the range or is less than the range, the observer callback is triggered.

-
- -- Return values - - **Table 7** Methods supported by the Observer object6+ - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

observe

-

callback: function

-

Subscribes to events of the observed object. The callback method is called when the value is greater than or less than the threshold.

-

unobserve

-

-

-

Unsubscribes from events of the observed object.

-
- -- Example - - ``` - // xxx.js - let observer = this.$element('broad').createIntersectionObserver({ - ratios: [0.2, 0.5], // number - }); - - observer.observe((isVisible, ratio)=> { - console.info('this element is ' + isVisible + 'ratio is ' + ratio) - }) - - observer.unobserve() - ``` +**Return value** + **Table 5** Rect6+ + +| Name | Type | Description | +| ------ | ------ | -------------- | +| width | number | Width of the element. | +| height | number | Height of the element. | +| left | number | Offset between the left boundary of the element and the window.| +| top | number | Offset between the upper boundary of the element and the window.| + +**Example** +```js +// xxx.js +var rect = this.$element('id').getBoundingClientRect(); +console.info(`current element position is ${rect.left}, ${rect.top}`); +``` +## createIntersectionObserver + +createIntersectionObserver(param?: ObserverParam): Observer + +Listens for the visibility of the element on the current page. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------------- | ---- | -------------- | +| param | ObserverParam | - | Observer callback.| + + **Table 6** ObserverParam6+ + +| Name | Type | Description | +| ------ | ------------------- | ------------------------ | +| ratios | Array<number> | Range for triggering the observer callback. If the component is not within the range, the observer callback is triggered.| + +**Return value** + + **Table 7** Methods supported Observer6+ + +| Method | Parameter | Description | +| --------- | ----------------------- | ----------------------------------- | +| observe | callback: function | Subscribes to events of the observed object. The callback method is called when the value is greater than or less than the threshold.| +| unobserve | - | Unsubscribes from events of the observed object. | + +**Example** +```js +// xxx.js +let observer = this.$element('broad').createIntersectionObserver({ + ratios: [0.2, 0.5], // number +}); + +observer.observe((isVisible, ratio)=> { + console.info('this element is ' + isVisible + 'ratio is ' + ratio) +}) + +observer.unobserve() +``` diff --git a/en/application-dev/reference/arkui-js/js-components-common-styles.md b/en/application-dev/reference/arkui-js/js-components-common-styles.md index 4a3a7f2973f4dca4b3e4b6b5267f35fd71eb3241..2c61ed94f1317ccbd3e429b6bc2a3516db28f337 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-styles.md +++ b/en/application-dev/reference/arkui-js/js-components-common-styles.md @@ -34,7 +34,7 @@ You can set universal styles for components in the **style** attribute or **.css | background | <linear-gradient> | - | Background. This attribute supports [gradient styles](../arkui-js/js-components-common-gradient.md) only and is not compatible with **background-color** or **background-image**.| | background-color | <color> | - | Background color. | | background-image | string | - | Background image. Both online and local image resources are supported. Currently, this attribute is not compatible with **background-color** or **background**.
Example:
- background-image: url("/common/background.png")
The SVG format is not supported.| -| background-size | - string
- <length> <length>
- <percentage> <percentage> | auto | Background image size.
- The **string** values are as follows:
- **contain**: Expands the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: Extends the background image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: Retains the original aspect ratio of the image.
- The two **** values are as follows:
Width and height of the background image. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
- The two **** values are as follows:
Width and height of the background image in percentage of the parent element. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.| +| background-size | - string
- <length> <length>
- <percentage> <percentage> | auto | Background image size.
- The **string** values are as follows:
- **contain**: Expands the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: Extends the background image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: Retains the original aspect ratio of the image.
- The two **\** values are as follows:
Width and height of the background image. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
- The two **\** values are as follows:
Width and height of the background image in percentage of the parent element. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.| | background-repeat | string | repeat | How a background image is repeatedly drawn. By default, a background image is repeated both horizontally and vertically.
- **repeat**: The image is repeated along the x-axis and y-axis at the same time.
- **repeat-x**: The image is repeated along the x-axis.
- **repeat-y**: The image is repeated along the y-axis.
- **no-repeat**: The image is not repeated.| | background-position | - string string
- <length> <length>
- <percentage> <percentage> | 0px 0px | - Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.
- **left**: leftmost in the horizontal direction.
- **right**: rightmost in the horizontal direction.
- **top**: top in the vertical direction.
- **bottom**: bottom in the vertical direction.
- **center**: center position.
- Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is **0 0**. The unit is pixel. If only one value is specified, the other one is **50%**.
- Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. **0% 0%** indicates the upper left corner. **100% 100%** indicates the lower right corner. If only one value is specified, the other one is **50%**.
- Using both **\** and **\**. | | box-shadow5+ | string | 0 | Syntax: **box-shadow: h-shadow v-shadow blur spread color**
Shadow style of the current component. The value includes the horizontal position (mandatory), vertical position (mandatory), fuzzy radius (optional, default value: **0**), extension distance (optional, default value: **0**), and color (optional, default value: **black**) of the shadow.
Example:
- box-shadow :10px 20px 5px 10px \#888888
- box-shadow :100px 100px 30px red
- box-shadow :-100px -100px 0px 40px | @@ -54,7 +54,7 @@ You can set universal styles for components in the **style** attribute or **.css | [start \| end]6+ | <length> \| <percentage> | - | **start | end** must be used together with **position** to determine the offset of an element.
- The **start** attribute specifies the start edge position of the element. This attribute defines the offset between the start edge of a positioned element and that of a block included in the element.
- The **end** attribute specifies the end edge position of the element. This attribute defines the offset between the end edge of a positioned element and that of a block included in the element. | | z-index6+ | number | - | Rendering sequence of child nodes under the same parent node. A child node with a larger value will be rendered later.
z-index does not support auto, and other styles such as opacity do not affect the rendering sequence of z-index.| | image-fill6+ | <color> | - | Fill color for SVG images. The following components are supported: **button** (icon attribute), **piece** (icon attribute), **search** (icon attribute), **input** (headericon attribute), **textarea** (headericon attribute), **image** (src attribute), and **toolbar-item** (icon attribute)
The **fill** color value in the SVG image file is replaced with the value of **image-fill** during rendering, and is valid only for the fill attribute that is declared in the SVG image.| -| clip-path6+ | [ <geometry-box> \| <basic-shape> ] \| none | - | Clip area of a component. Only the content within this area is displayed.
****: applicable scope of the clip area's width and height. The default value is **border-box**. Available values are as follows:
- **margin-box**: The width and height includes the margin.
- **border-box**: The width and height includes the border.
- **padding-box**: The width and height includes the padding.
- **content-box**: The width and height does not include any margin, border, or padding.
****: shape of the clip area. Available values include:
- **inset**, in the format of inset( \{1,4} [ round \<'border-radius'> ]? ).
- **circle**, in the format of circle( [ \ ]? [ at <percentage> <percentage> ]? ).
- **ellipse**, in the format of ellipse( [ \{2} ]? [ at <percentage> <percentage> ]? ).
- **polygon**, in the format of polygon( [ \ \ ]\# ).
- **path**, in the format of path( \ ).| +| clip-path6+ | [ <geometry-box> \| <basic-shape> ] \| none | - | Clip area of a component. Only the content within this area is displayed.
**\**: applicable scope of the clip area's width and height. The default value is **border-box**. Available values are as follows:
- **margin-box**: The width and height includes the margin.
- **border-box**: The width and height includes the border.
- **padding-box**: The width and height includes the padding.
- **content-box**: The width and height does not include any margin, border, or padding.
**\**: shape of the clip area. Available values include:
- **inset**, in the format of inset( \{1,4} [ round \<'border-radius'> ]? ).
- **circle**, in the format of circle( [ \ ]? [ at <percentage> <percentage> ]? ).
- **ellipse**, in the format of ellipse( [ \{2} ]? [ at <percentage> <percentage> ]? ).
- **polygon**, in the format of polygon( [ \ \ ]\# ).
- **path**, in the format of path( \ ).| | mask-image6+ | - <linear-gradient>
- string | - | Image used for the mask of a component:
Gradient color mask, for example:
linear-gradient(to left, black, white)
Solid color mask, for example:
linear-gradient(to right, grey , grey)
Mask filled by a local SVG image, for example, **url(common/mask.svg)**| | mask-size6+ | - string
- <length><length>
- <percentage> <percentage> | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.
The **string** values are as follows:
- **contain**: Expands the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: Extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: Retains the original aspect ratio of the image.
The two **\** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
The two **\** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default. | | mask-position6+ | - string string
- <length> <length>
- <percentage> <percentage> | 0px 0px | Display position of the mask image. The setting is valid only when **mask-image** is set to an image source. Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.
The **string** values are as follows:
- **left**: leftmost in the horizontal direction.
- **right**: rightmost in the horizontal direction.
- **top**: top in the vertical direction.
- **bottom**: bottom in the vertical direction.
- **center**: center position.
Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is **0 0**. The unit is pixel. If only one value is specified, the other one is **50%**.
Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. **0% 0%** indicates the upper left corner. **100% 100%** indicates the lower right corner. If only one value is specified, the other one is **50%**.
Using both **\** and **\**. | diff --git a/en/application-dev/reference/arkui-js/js-components-container-badge.md b/en/application-dev/reference/arkui-js/js-components-container-badge.md index b080f605d5ef2f95faa565d505965190f83db9e4..c0855efd572677c06214c3bd4900fbfff05a9684 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-badge.md +++ b/en/application-dev/reference/arkui-js/js-components-container-badge.md @@ -1,192 +1,71 @@ -# badge +# badge -The **** component is used to mark new events that require user attention in your application. +> **NOTE** +> +> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component is used to mark new events that require user attention in your application. + + +## Required Permissions None -## Child Components + +## Child Components This component supports only one child component. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->If multiple child components are used, only the first one takes effect by default. - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

placement

-

string

-

rightTop

-

No

-

Position of a number or dot badge. Available values are as follows:

-
  • right: on the right border of the component.
  • rightTop: in the upper right corner of the component border.
  • left: on the left border of the component.
-

count

-

number

-

0

-

No

-

Number of notifications displayed via the badge. The default value is 0. If the number of notifications is greater than 0, the badge changes from a dot to the number. If this attribute is not set or the value is less than or equal to 0, the badge is a dot.

-
NOTE:

When the count value is greater than the maxcount value, maxcount+ is displayed.

-

The largest integer value supported for count is 2147483647.

-
-

visible

-

boolean

-

false

-

No

-

Whether to display the badge. The value true means that the badge shows up when a new notification is received. To use a number badge, set the count attribute.

-

maxcount

-

number

-

99

-

No

-

Maximum number of notifications. When the number of new notifications exceeds the value of this attribute, maxcount+ is displayed, for example, 99+.

-
NOTE:

The largest integer value supported for maxcount is 2147483647.

-
-

config

-

BadgeConfig

-

-

-

No

-

Configuration of the badge.

-

label6+

-

string

-

-

-

No

-

Text of the new notification displayed via the badge.

-
NOTE:

When this attribute is set, attributes count and maxcount do not take effect.

-
-
- -**Table 1** BadgeConfig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

badgeColor

-

<color>

-

#fa2a2d

-

No

-

Background color of the badge

-

textColor

-

<color>

-

#ffffff

-

No

-

Text color of the number badge

-

textSize

-

<length>

-

10px

-

No

-

Text size of the number badge

-

badgeSize

-

<length>

-

6px

-

No

-

Default size of the dot badge

-
- -## Styles - -Styles in [Universal Styles](js-components-common-styles.md) are supported. - ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The total size of child components must be smaller than or equal to that of the **** component. Otherwise, the child components cannot be displayed. - -## Events - -Events in [Universal Events](js-components-common-events.md) are supported. - -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example +> **NOTE** +> +> If multiple child components are used, only the first one takes effect by default. -``` + +## Attributes + +In addition to the [universal attributes](js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ----------- | -------- | ---- | ---------------------------------------- | +| placement | string | rightTop | No | Position of a number or dot badge. Available values are as follows:
- **right**: on the right border of the component.
- **rightTop**: in the upper right corner of the component border.
- **left**: on the left border of the component.| +| count | number | 0 | No | Number of notifications displayed via the badge. The default value is **0**. If the number of notifications is greater than 0, the badge changes from a dot to the number. If this attribute is not set or the value is less than or equal to 0, the badge is a dot.
When the **count** value is greater than the **maxcount** value, *maxcount***+** is displayed. The largest integer value supported for **count** is **2147483647**.| +| visible | boolean | false | No | Whether to display the badge. The value **true** means that the badge shows up when a new notification is received. To use a number badge, set the **count** attribute.| +| maxcount | number | 99 | No | Maximum number of notifications. When the number of new notifications exceeds the value of this attribute, *maxcount***+** is displayed, for example, **99+**.
The largest integer value supported for **maxcount** is **2147483647**.| +| config | BadgeConfig | - | No | Configuration of the badge. | +| label6+ | string | - | No | Text of the new notification displayed via the badge.
When this attribute is set, attributes **count** and **maxcount** do not take effect.| + +**Table 1** BadgeConfig + +| Name | Type | Default Value | Mandatory | Description | +| ---------- | -------------- | -------- | ---- | ------------ | +| badgeColor | <color> | \#fa2a2d | No | Background color of the badge. | +| textColor | <color> | \#ffffff | No | Text color of the number badge.| +| textSize | <length> | 10px | No | Text size of the number badge.| +| badgeSize | <length> | 6px | No | Default size of the dot badge. | + + +## Styles + +The [universal styles](../arkui-js/js-components-common-styles.md) are supported. + +> **NOTE** +> +> The total size of child components must be smaller than or equal to that of the **\** component. Otherwise, the child components cannot be displayed. + + +## Events + +The [universal events](../arkui-js/js-components-common-events.md) are supported. + + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +```html
@@ -198,7 +77,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported.
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -219,7 +98,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -``` +```js // xxx.js export default { data:{ @@ -231,5 +110,4 @@ export default { } ``` -![](figures/figures1.png) - +![figures1](figures/figures1.png) diff --git a/en/application-dev/reference/arkui-js/js-components-container-dialog.md b/en/application-dev/reference/arkui-js/js-components-container-dialog.md index 3428de3d7aa224dcd711a80019f9309197cb629b..a37adca994facb60950bc6d072541108509680c8 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-dialog.md +++ b/en/application-dev/reference/arkui-js/js-components-container-dialog.md @@ -1,126 +1,67 @@ -# dialog +# dialog -The **** component is a custom pop-up container. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component is a custom dialog box. + +## Required Permissions None -## Child Components - -A single child component is supported. - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

dragable7+

-

boolean

-

false

-

No

-

Whether the pop-up can be dragged.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- The **** component does not support the **focusable** and **click-effect** attributes. - -## Styles - -Only the **width**, **height**, **margin**, **margin-\[left|top|right|bottom\]**, and **margin-\[start|end\]** styles in [Universal Styles](js-components-common-styles.md) are supported. - -## Events - -Events in [Universal Events](js-components-common-events.md) are not supported. The following table lists the supported event. - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

cancel

-

-

-

Triggered when a user taps a non-dialog area to cancel the pop-up.

-

show7+

-

-

-

Triggered when the pop-up is displayed.

-

close7+

-

-

-

Triggered when the pop-up is closed.

-
- -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are not supported. The following table lists the supported methods. - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

show

-

-

-

Shows a dialog box.

-

close

-

-

-

Closes a dialog box.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->Attributes and styles of a **** component cannot be dynamically updated. - -## Example Code -``` +## Child Components + +This component supports only one child component. + + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| --------------------- | ------- | ----- | ---- | ------------ | +| dragable7+ | boolean | false | No | Whether the dialog box can be dragged.| + +> **NOTE** +> +> The **\** component does not support the **focusable** and **click-effect** attributes. + + +## Styles + +Only the **width**, **height**, **margin**, **margin-[left|top|right|bottom]**, and **margin-[start|end]** styles in [Universal Styles](../arkui-js/js-components-common-styles.md) are supported. + + +## Events + +The following events are supported. The [universal events](../arkui-js/js-components-common-events.md) are not supported. + +| Name | Parameter | Description | +| ------------------ | ---- | -------------------------- | +| cancel | - | Triggered when a user touches an area outside the dialog box to cancel the dialog box.| +| show7+ | - | Triggered when the dialog box is displayed. | +| close7+ | - | Triggered when the dialog box is closed. | + + +## Methods + +The following methods are supported. The [universal methods](../arkui-js/js-components-common-methods.md) are not supported. + +| Name | Parameter | Description | +| ----- | ---- | ------ | +| show | - | Shows a dialog box.| +| close | - | Close the dialog box.| + +> **NOTE** +> +> Attributes and styles of a **\** component cannot be dynamically updated. + + +## Example + +```html
@@ -140,7 +81,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are not suppor
``` -``` +```css /* xxx.css */ .doc-page { flex-direction: column; @@ -189,31 +130,31 @@ Methods in [Universal Methods](js-components-common-methods.md) are not suppor } ``` -``` +```js // xxx.js import prompt from '@system.prompt'; export default { - showDialog(e) { + showDialog() { this.$element('simpledialog').show() }, - cancelDialog(e) { + cancelDialog() { prompt.showToast({ message: 'Dialog cancelled' }) }, - cancelSchedule(e) { + cancelSchedule() { this.$element('simpledialog').close() prompt.showToast({ message: 'Successfully cancelled' }) }, - setSchedule(e) { + setSchedule() { this.$element('simpledialog').close() prompt.showToast({ message: 'Successfully confirmed' }) }, - doubleclick(e){ + doubleclick(){ prompt.showToast({ message: 'doubleclick' }) @@ -221,5 +162,4 @@ export default { } ``` -![](figures/4.gif) - +![4](figures/4.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-div.md b/en/application-dev/reference/arkui-js/js-components-container-div.md index 72f9ef211c9a55a003982c02089ef15641e840b6..9a2976b1a7b00769300795475c59a24f25364e02 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-div.md +++ b/en/application-dev/reference/arkui-js/js-components-container-div.md @@ -1,11 +1,10 @@ # div -The **\
** component is a basic container that is used as the root node of the page structure or is used to group the content. - > **NOTE** > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +The **\
** component is a basic container that is used as the root node of the page structure or is used to group the content. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-components-container-form.md b/en/application-dev/reference/arkui-js/js-components-container-form.md index 23d52f34982ef8067457fac1bb81a02b85c471e8..c99f5c99e3cc41ee2bff31d6dcb3e9435a7379b3 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-form.md +++ b/en/application-dev/reference/arkui-js/js-components-container-form.md @@ -1,81 +1,56 @@ -# form +# form -The **** component allows the content in **input** elements to be submitted and reset. +> **NOTE** +> +> This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\
** component allows the content in **input** elements to be submitted and reset. + + +## Required Permissions None -## Child Component + +## Child Components Supported -## Attributes - -Attributes in [Universal Attributes](js-components-common-attributes.md) are supported. - -## Styles - -Styles in [Universal Styles](js-components-common-styles.md) are supported. - -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - - - - - - - - - - - - - - - -

Name

-

Parameters

-

Description

-

submit

-

FormResult

-

Triggered when the Submit button is touched.

-

reset

-

-

-

Triggered when the Reset button is clicked.

-
- -**Table 1** FormResult - - - - - - - - - - - - -

Name

-

Type

-

Description

-

value

-

Object

-

Values of name and value of the input element.

-
- -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example -``` +## Attributes + +The [universal attributes](../arkui-js/js-components-common-attributes.md) are supported. + + +## Styles + +The [universal styles](../arkui-js/js-components-common-styles.md) are supported. + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +| Name| Parameter| Description| +| -------- | -------- | -------- | +| submit | FormResult | Triggered when the **Submit** button is touched.| +| reset | - | Triggered when the **Reset** button is clicked.| + +**Table 1** FormResult + +| Name| Type| Description| +| -------- | -------- | -------- | +| value | Object | Values of **name** and **value** of the input element.| + + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +```html
@@ -93,7 +68,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. ``` -``` +```js // xxx.js export default{ onSubmit(result) { @@ -106,5 +81,4 @@ export default{ } ``` -![](figures/001.gif) - +![001](figures/001.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md b/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md index 94c1d783105f88d9b17b78737f92d91615633b49..1a9fa13727b5fbd31d257379ede19e045df95cfa 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md +++ b/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md @@ -1,145 +1,68 @@ -# list-item-group +# list-item-group -**** is a child component of **<[list](js-components-container-list.md)\>** and is used to group items in a list. By default, the width of **** is equal to that of ****. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -- To use this component, you must set the **columns** attribute of the parent component **** to **1**. Otherwise, **** is not displayed. -- You can customize the width of each ****. However, if you retain the default value **stretch** of **align-items** for the parent component ****, the width of **** is equal to that of ****. You can set **align-items** to other values rather than **stretch** to make the customized **** width take effect. +**\** is a child component of **[\](../arkui-js/js-components-container-list.md)** and is used to group items in a list. By default, the width of **\** is equal to that of **\**. -## Required Permissions + +- To use this component, you must set the **columns** attribute of the parent component **\** to **1**. Otherwise, this component is not displayed. + +- You can customize the width of each **\**. However, if you retain the default value **stretch** of **align-items** for the parent component **\**, the width of **\** is equal to that of **\**. To make the customized **\** width take effect, set **align-items** to other values rather than **stretch**. + +## Required Permissions None -## Child Components - -Only **<[list-item](js-components-container-list-item.md)\>** are supported. - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

default

-

No

-

Type of the list-item-group. A list supports multiple list-item-group types. The same type of list-item-groups should have the same view layout after being rendered. When the type is fixed, replace the if attribute with the show attribute to ensure that the view layout remains unchanged.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- **id** in the common attributes is used to identify a group. The input parameters of related functions and event information in the list also use **id** to uniquely identify a group. - -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

flex-direction

-

string

-

row

-

No

-

Main axis direction of the container. Available values are as follows:

-
  • column: Items are placed vertically from top to bottom.
  • row: Items are placed horizontally from left to right.
-

justify-content

-

string

-

flex-start

-

No

-

How items are aligned along the main axis of the current row in the container. Available values are as follows:

-
  • flex-start: Items are packed towards the start row.
  • flex-end: Items are packed towards the end row.
  • center: Items are centered along the row.
  • space-between: Items are positioned with space between the rows.
  • space-around: Items are positioned with space before, between, and after the rows.
  • space-evenly5+: Items are arranged with even space between each two.
-
- -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

groupclick

-

{ groupid: string }

-

Triggered when a group is clicked.

-

groupid: ID of the group that is clicked.

-

groupcollapse

-

{ groupid: string }

-

Triggered when a group is collapsed.

-

groupid: ID of the group collapsed.

-

If the parameter is not carried or groupid is left empty, all groups are collapsed.

-

groupexpand

-

{ groupid: string }

-

Triggered when a group is expanded.

-

groupid: ID of the group expanded.

-

If the parameter is not carried or groupid is left empty, all groups are expanded.

-
- -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example -``` +## Child Components + +Only the **[\](../arkui-js/js-components-container-list-item.md)** component is supported. + + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---- | ------ | ------- | ---- | ---------------------------------------- | +| type | string | default | No | Type of the list item group. A list supports multiple list item group types. The same type of list item groups must have the same view layout after being rendered. If the type is fixed, replace the **if** attribute with the **show** attribute to ensure that the view layout remains unchanged.| + +> **NOTE** +> +> **id** in the universal attributes is used to identify a group. The input parameters of related functions and event information in the list also use **id** to uniquely identify a group. + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| --------------- | ------ | ---------- | ---- | ---------------------------------------- | +| flex-direction | string | row | No | Main axis direction of the flex container, which defines how items are placed in the container. Available values are as follows:
- **column**: Items are placed vertically from top to bottom.
- **row**: Items are placed horizontally from left to right.| +| justify-content | string | flex-start | No | How items are aligned along the main axis of the flex container. Available values are as follows:
- **flex-start**: Items are packed toward the start edge of the container along the main axis.
- **flex-end**: Items are packed toward the end edge of the container along the main axis.
- **center**: Items are packed toward the center of the container along the main axis.
- **space-between**: Items are positioned with space between the rows.
- **space-around**: Items are positioned with space before, between, and after the rows.
- **space-evenly**5+: Items are distributed within the container along the main axis, with even space between each two.| + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +| Name | Name | Description | +| ------------- | ---------------------------------- | ---------------------------------------- | +| groupclick | { groupid: string } | Triggered when a group is clicked.
**groupid**: ID of the group that is clicked. | +| groupcollapse | { groupid: string } | Triggered when a group is collapsed.
**groupid**: ID of the group that is collapsed.
If the parameter is not carried or **groupid** is left empty, all groups are collapsed.| +| groupexpand | { groupid: string } | Triggered when a group is expanded.
**groupid**: ID of the group that is expanded.
If the parameter is not carried or **groupid** is left empty, all groups are expanded.| + + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +```html
@@ -171,7 +94,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported.
``` -``` +```css /* xxx.css */ .doc-page { flex-direction: column; @@ -199,13 +122,14 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -``` +```js // xxx.js import prompt from '@system.prompt'; export default { data: { direction: 'column', - list: [] + list: [], + listAdd: [] }, onInit() { this.list = [] @@ -246,5 +170,4 @@ export default { } ``` -![](figures/list6.gif) - +![list6](figures/list6.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-list-item.md b/en/application-dev/reference/arkui-js/js-components-container-list-item.md index fe50d50cf428849f67a4a0d1a48d62874e80d6b1..2d13225e7d8fac61e878abaca022a66da1d8af15 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-list-item.md +++ b/en/application-dev/reference/arkui-js/js-components-container-list-item.md @@ -1,154 +1,56 @@ -# list-item +# list-item -**** is a child component of the **<[list](js-components-container-list.md)\>** component and is used to display items in a list. You can customize the width of each ****. However, if you retain the default value **stretch** of **align-items** for the parent component ****, the width of **** is equal to that of ****. You can set **align-items** to other values rather than **stretch** to make the customized **** width take effect. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +**\** is a child component of the **[\](../arkui-js/js-components-container-list.md)** component and is used to display items in a list. You can customize the width of each **\**. However, if you retain the default value **stretch** of **align-items** for the parent component **\**, the width of **\** is equal to that of **\**. To make the customized **\** width take effect, set **align-items** to other values rather than **stretch**. + +## Required Permissions None -## Child Components + +## Child Components This component supports only one child component. -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

default

-

No

-

Type of the list-item. A list can contain multiple list-item types. The same type of list items should have the same view layout after being rendered. When the type is fixed, replace the if attribute with the show attribute to ensure that the view layout remains unchanged.

-

primary

-

boolean

-

false

-

No

-

The value true indicates that the item is the primary item in the group, which is the item that appears in a collapsed group. If there is more than one item marked as primary, the first one is the primary item. If there is no item marked as primary, the first item is the primary item.

-

section

-

string

-

-

-

No

-

String used to match this item. This attribute can be left empty. The value cannot be dynamically updated. In a list item group, only the string set for the primary item is valid.

-

sticky

-

string

-

none

-

No

-

Whether the current item sticks in place at the top, and the effect when it disappears. This attribute supports vertical lists only and is invalid for items in a group.

-
  • none: The current item does not stick at the top.
  • normal: The current item sticks at the top and disappears with a sliding effect.
  • opacity: The current item sticks at the top and disappears gradually. This option is only supported on wearables.
-

clickeffect5+

-

boolean

-

true

-

No

-

Whether an effect is displayed when the current item is clicked.

-
  • false: No effect is displayed when the item is clicked.
  • true: An effect is displayed when the item is clicked.
-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

column-span

-

<number>

-

1

-

No

-

Number of columns occupied by the current list-item in the list. By default, the list-item occupies one column. This attribute is valid only when the list contains multiple columns.

-
- -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

sticky

-

{ state: boolean }

-

Callback events for a sticky component.

-

value: false: The current item is not in the sticky state.

-

value: true: The current item is in the sticky state.

-

This event is supported only when the item is configured with the sticky attribute.

-
- -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example - -For details, see the [list example code](js-components-container-list.md#example). +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| type | string | default | No| Type of the list-item. A list can contain multiple list-item types. The same type of list items should have the same view layout after being rendered. When the type is fixed, replace the **if** attribute with the **show** attribute to ensure that the view layout remains unchanged.| +| primary | boolean | false | No| Whether the item is the primary item in the group. The value **true** indicates that the item is the primary item in the group, which is the item that appears in a collapsed group. If there is more than one item marked as primary, the first one is the primary item. If there is no item marked as primary, the first item is the primary item.| +| section | string | - | No| String used to match the item. This attribute can be left empty. The value cannot be dynamically updated. In a list item group, only the string set for the primary item is valid.| +| sticky | string | none | No| Whether the current item sticks in place at the top, and the effect when it disappears. This attribute supports vertical lists only and is invalid for items in a group.
- **none**: The current item does not stick at the top.
- **normal**: The current item sticks at the top and disappears with a sliding effect.
- **opacity**: The current item sticks at the top and disappears gradually. This option is only supported on wearables.| +| clickeffect5+ | boolean | true | No| Whether an effect is displayed when the current item is clicked.
- **false**: No effect is displayed when the item is clicked.
- **true**: An effect is displayed when the item is clicked.| + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| column-span | <number> | 1 | No| Number of columns occupied by the current list-item in the list. By default, the list-item occupies one column. This attribute is valid only when the list contains multiple columns.| + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +| Name| Parameter| Description| +| -------- | -------- | -------- | +| sticky | { state: boolean } | Callback event for a sticky component.
**value: false**: The current item is not in the sticky state.
**value: true**: The current item is in the sticky state.
This event is supported only when the item is configured with the **sticky** attribute.| + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +For details, see [Example in list](../arkui-js/js-components-container-list.md#example). diff --git a/en/application-dev/reference/arkui-js/js-components-container-list.md b/en/application-dev/reference/arkui-js/js-components-container-list.md index 62d15baf7ecd6405327a457190879d235fe0418e..640c6c420ce81d299b7d12a1b67cca42b543ea1b 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-list.md +++ b/en/application-dev/reference/arkui-js/js-components-container-list.md @@ -1,630 +1,105 @@ -# list +# list -The **** component provides a list container that presents a series of list items arranged in a column with the same width. Lists support presentations of the same data in a multiple and coherent row style, for example, images and texts. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component provides a list container that presents a series of list items arranged in a column with the same width. It supports presentations of the same type of data in a multiple and coherent row style, for example, images or text. -N/A +## Required Permissions -## Child Components +None -<[list-item](js-components-container-list-item-group.md)\> and <[list-item-group](js-components-container-list-item.md)\> -## Attributes +## Child Components -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +The **[\](../arkui-js/js-components-container-list-item-group.md)** and **[\](../arkui-js/js-components-container-list-item.md)** components are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

scrollpage

-

boolean

-

false

-

No

-

Whether to scroll the non-list part on the top of the list page out of the visible area with the list. The value can be true (scrolls the non-list part out) or false (does not scroll the non-list part out). This attribute is not available when the direction is row.

-

cachedcount

-

number

-

0

-

No

-

Minimum number of cached list items when the long list is loaded with delay.

-

When the number of list items cached outside the visible area is less than the value of this attribute, a requestitem event is triggered.

-

scrollbar

-

string

-

off

-

No

-

Display mode of the side scrollbar. (Currently, only the vertical scrollbar is supported.)

-
  • off: No display
  • auto: Displayed on demand (The side scrollbar is displayed when touched and disappears 2s later.)
  • on: Always displayed
-

scrolleffect

-

string

-

spring

-

No

-

Scroll effect. Available values are as follows:

-
  • spring: Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded.
  • fade: Similar to the physical dynamic effect of fade. When you scroll to the edge, a wave shape fades. The fade changes according to the speed and scrolling distance.
  • no: No effect after the scrollbar is moved to the edge.
-

indexer

-

boolean | Array<string>

-

false

-

No

-

Whether to display the alphabetical index bar on the sidebar. If this attribute is set to true or a customized indexer, the index bar is displayed at the right boundary of the list. Example:

-

"indexer" : "true" indicates the default alphabetical indexer.

-

"indexer" : "false" indicates no indexer.

-

"indexer": ['#', '1', '2', '3', '4', '5', '6', '7', '8'] indicates a customized index. You must include "#" when using a customized indexer.

-
NOTE:
  • This attribute is valid only when flex-direction is set to column and columns is set to 1.
  • This attribute must be used together with the section attribute of <list-item>.
-
-

indexercircle5+

-

boolean

-

-

-

No

-

Whether to use a circle indexer.

-

The default value is true for wearables and false for other device types. This attribute is invalid if indexer is set to false.

-

indexermulti5+

-

boolean

-

false

-

No

-

Whether to use a multi-language indexer.

-

This attribute is invalid if indexer is set to false.

-

indexerbubble5+

-

boolean

-

true

-

No

-

Whether to display the bubble effect when switching among indexes.

-

This attribute is invalid if indexer is set to false.

-

divider5+

-

boolean

-

false

-

No

-

Whether list items are separated by dividers.

-

For details about divider styles, see divider-color, divider-height, divider-length, and divider-origin in the Styles table.

-

shapemode

-

string

-

default

-

No

-

Shape of the side scrollbar.

-
  • default: not specified (following the theme)
  • rect: rectangle
  • round: circle
-

updateeffect

-

boolean

-

false

-

No

-

Whether a dynamic effect is displayed when an item in the list is deleted or added.

-
  • false: No dynamic effect is displayed.
  • true: A dynamic effect is displayed when an item is added or deleted.
-

chainanimation5+

-

boolean

-

false

-

No

-

Whether to display chained animations on this list when it slides or its top and bottom are dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.

-
  • false: Chained animations are displayed.
  • true: No chained animation is displayed.
    NOTE:
    • Dynamic modification is not supported.
    • This attribute does not take effect if an indexer is used.
    • If this attribute is true, the sticky attributes set for <list-item> components do not take effect.
    -
    -
-

initialindex

-

number

-

0

-

No

-

Item to be displayed at the start position of the viewport when the current list is loaded for the first time. The default value is 0, indicating that the first item is displayed.

-

The setting does not take effect in any of the following cases:

-
  • The value you set is greater than the index of the last item.
  • The initialoffset attribute is set.
  • indexer or scrollpage is set to true.
-

initialoffset

-

<length>

-

0

-

No

-

Start offset of the viewport when the current list is loaded for the first time. The offset must not exceed the scrolling range of the current list. If exceeded, the offset is truncated to the maximum value of the scrolling range. This attribute does not take effect if indexer or scrollpage is set to true.

-

selected5+

-

string

-

-

-

No

-

Selected item in the current list. The value can be a section value of any list items.

-
-## Styles +## Attributes -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

divider-color5+

-

<color>

-

transparent

-

No

-

Item divider color. This style is valid only when the divider attribute of <list> is set to true.

-

divider-height5+

-

<length>

-

1

-

No

-

Item divider height. This style is valid only when the divider attribute of <list> is set to true.

-

divider-length5+

-

<length>

-

The main axis width

-

No

-

Item divider length. If this style is not set, the maximum length is the width of the main axis, and the actual length depends on the divider-origin parameter. This style is valid only when the divider attribute of <list> is set to true.

-

divider-origin5+

-

<length>

-

0

-

No

-

Item divider offset relative to the start point of the main axis. This style is valid only when the divider attribute of <list> is set to true.

-

flex-direction

-

string

-

-

column

-

No

-

Main axis direction of the flex container. It specifies how items are placed in the flex container.

-
  • column: The y-axis is the maim axis.
  • row: The x-axis is the main axis.
-

For the <list> component, the default value is column. For other components, the default value is row.

-

columns

-

number

-

1

-

No

-

Number of columns displayed in the cross axis direction of the list. The default value is 1.

-
NOTE:

When multiple columns are set, the columns are evenly distributed on the cross axis of the <list> component. The size of each column is the same.

-
-

align-items

-

string

-

stretch

-

No

-

Alignment of items in each column on the cross axis. Available values are as follows:

-
  • stretch: Items are stretched to the same height or width as the container in the cross axis direction.
  • flex-start: Items are aligned to the start of the cross axis.
  • flex-end: Items are aligned to the end of the cross axis.
  • center: Items are aligned in the middle of the cross axis.
    NOTE:

    This style takes effect only on items of each column. Columns are evenly distributed.

    -
    -
-

item-extent

-

<length> | <percentage>

-

-

-

No

-

Size of an internal item. When a percentage is set, the value indicates the percentage of the length in the main axis direction relative to the list viewpoint.

-

fade-color

-

<color>

-

grey

-

No

-

Color of the physical dynamic effect. This attribute is valid only when scrolleffect is set to fade.

-

scrollbar-color6+

-

<color>

-

-

-

No

-

Color of the scrollbar.

-

scrollbar-width6+

-

<length>

-

-

-

No

-

Width of the scrollbar.

-

scrollbar-offset6+

-

<length>

-

0

-

No

-

Offset between the scrollbar and the default position of the list. The value must be a positive number. The default position is on the right edge of the list. You can adjust the horizontal position of the scrollbar by setting this offset. If the scrollbar is drawn outside the list and the parent component of the list is capable of cropping, the scrollbar will be cropped.

-
+| Name | Type | Default Value | Mandatory | Description | +| --------------------------- | ---------------------------------------- | ------- | ---- | ---------------------------------------- | +| scrollpage | boolean | false | No | Whether to scroll the non-list part on the top of the list page out of the visible area with the list. The value can be **true** (scrolls the non-list part out) or **false** (does not scroll the non-list part out). This attribute is not available when the direction is **row**.| +| cachedcount | number | 0 | No | Minimum number of cached list items when a long list is loaded with delay.
When the number of list items cached outside the visible area is less than the value of this attribute, a **requestitem** event is triggered.| +| scrollbar | string | off | No | Display mode of the side scrollbar. (Currently, only the vertical scrollbar is supported.)
- **off**: no display.
- **auto**: displayed on demand (The side scrollbar is displayed when touched and disappears 2s later.).
- **on**: always displayed.| +| scrolleffect | string | spring | No | Scroll effect. Available values are as follows:
- **spring**: Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded.
- **fade**: Similar to the physical dynamic effect of fade. When you scroll to the edge, a wave shape fades. The fade changes according to the speed and scrolling distance.
- **no**: No effect after the scrollbar is moved to the edge.| +| indexer | boolean \| Array<string> | false | No | Whether to display the alphabetical index bar on the sidebar. If this attribute is set to **true** or a customized indexer, the index bar is displayed at the right boundary of the list. Example:
**"indexer" : "true"** indicates the default alphabetical indexer.
**"indexer" : "false"** indicates no indexer.
"indexer": ['#', '1', '2', '3', '4', '5', '6', '7', '8'] indicates a customized index. You must include **"#"** when using a customized indexer.
This **indexer** attribute is valid only when **flex-direction** is set to **column** and **columns** is set to **1**.
This attribute must be used together with the **[section](../arkui-js/js-components-container-list-item.md#attributes)** attribute of **\**.| +| indexercircle5+ | boolean | - | No | Whether to use a circle indexer.
The default value is **true** for wearables and **false** for other device types. This attribute is invalid if **indexer** is set to **false**.| +| indexermulti5+ | boolean | false | No | Whether to use a multi-language indexer.
This attribute is invalid if **indexer** is set to **false**. | +| indexerbubble5+ | boolean | true | No | Whether to display the bubble effect when switching among indexes.
This attribute is invalid if **indexer** is set to **false**. | +| divider5+ | boolean | false | No | Whether list items are separated by dividers.
For details about divider styles, see **divider-color**, **divider-height**, **divider-length**, and **divider-origin** in the **Styles** table.| +| shapemode | string | default | No | Shape of the side scrollbar.
- **default**: not specified (following the theme).
- **rect**: rectangle.
- **round**: circle.| +| updateeffect | boolean | false | No | Whether a dynamic effect is displayed when an item in the list is deleted or added.
- **false**: No dynamic effect is displayed.
- **true**: A dynamic effect is displayed when an item is added or deleted.| +| chainanimation5+ | boolean | false | No | Whether to display chained animations on this list when it slides or its top and bottom are dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
- **false**: Chained animations are displayed.
- **true**: No chained animation is displayed.
Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
This attribute does not take effect if an indexer is used.
If this attribute is **true**, the **sticky** attributes set for **\** components do not take effect.| +| initialindex | number | 0 | No | Item displayed at the start position of the viewport when the current list is loaded for the first time. The default value is **0**, indicating that the first item is displayed. If the number you set is greater than the index of the last item, the setting does not take effect. When the **initialoffset** attribute is set, this attribute does not take effect. This attribute does not take effect if **indexer** or **scrollpage** is set to **true**.| +| initialoffset | <length> | 0 | No | Start offset of the viewport when the current list is loaded for the first time. The offset must not exceed the scrolling range of the current list. If exceeded, the offset is truncated to the maximum value of the scrolling range. This attribute does not take effect if **indexer** or **scrollpage** is set to **true**.| +| selected5+ | string | - | No | Selected item in the current list. The value can be a **section** value of any list items.| -## Events -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. +## Styles - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

indexerchange5+

-

{ local: booleanValue }

-

Triggered when the indexer switches between local and alphabetic indexers. This parameter takes effect only when both indexer and indexermulti are set to true. The value of booleanValue can be:

-
  • true: The local index is displayed.
  • false: The alphabetic index is displayed.
-

scroll

-

{ scrollX: scrollXValue, scrollY: scrollYValue, scrollState: stateValue }

-

Triggered to indicate the offset and status of list scrolling.

-

stateValue: 0: The list is not scrolling.

-

stateValue: 1: The list is scrolling along with user's touches.

-

stateValue: 2: The list is scrolling after the touches stop.

-

scrollbottom

-

-

-

Triggered when the list is scrolled to the bottom.

-

scrolltop

-

-

-

Triggered when the list is scrolled to the top.

-

scrollend

-

-

-

Triggered when the list stops scrolling.

-

scrolltouchup

-

-

-

Triggered when the list continues scrolling after the user lifts their fingers.

-

requestitem

-

-

-

Triggered for a request to create a list-item.

-

This event is triggered when the number of cached list-items outside the visible area is less than the value of cachedcount during long list loading with delay.

-

rotate7+

-

{ rotateValue: number }

-

Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables.

-
+In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -## Methods +| Name | Type | Default Value | Mandatory | Description | +| ----------------------------- | ---------------------------------------- | ----------- | ---- | ---------------------------------------- | +| divider-color5+ | <color> | transparent | No | Item divider color. This style is valid only when the **divider** attribute of **\** is set to **true**. | +| divider-height5+ | <length> | 1 | No | Item divider height. This style is valid only when the **divider** attribute of **\** is set to **true**. | +| divider-length5+ | <length> | Main axis width | No | Item divider length. If this style is not set, the maximum length is the width of the main axis, and the actual length depends on the **divider-origin** parameter. This style is valid only when the **divider** attribute of **\** is set to **true**.| +| divider-origin5+ | <length> | 0 | No | Item divider offset relative to the start point of the main axis. This style is valid only when the **divider** attribute of **\** is set to **true**.| +| flex-direction | string | column | No | Main axis direction of the flex container. It specifies how items are placed in the flex container.
- **column**: The y-axis is the main axis.
- **row**: The x-axis is the main axis.
For the **\** component, the default value is **column**. For other components, the default value is **row**.| +| columns | number | 1 | No | Number of columns displayed in the cross axis direction of the list. The default value is **1**.
When multiple columns are set, the columns are evenly distributed on the cross axis of the **\** component. The size of each column is the same.| +| align-items | string | stretch | No | Alignment of items in each column on the cross axis. Available values are as follows:
- **stretch**: Items are stretched to the same height or width as the container in the cross axis direction.
- **flex-start**: Items are aligned to the start of the cross axis.
- **flex-end**: Items are aligned to the end of the cross axis.
- **center**: Items are aligned in the center of the cross axis.
This style takes effect only on items of each column. Columns are evenly distributed.| +| item-extent | <length> \| <percentage> | - | No | Size of an internal item. When a percentage is set, the value indicates the percentage of the length in the main axis direction relative to the list viewpoint.| +| fade-color | <color> | grey | No | Color of the physical dynamic effect. This attribute is valid only when **scrolleffect** is set to **fade**. | +| scrollbar-color6+ | <color> | - | No | Color of the scrollbar. | +| scrollbar-width6+ | <length> | - | No | Width of the scrollbar. | +| scrollbar-offset6+ | <length> | 0 | No | Offset between the scrollbar and the default position of the list. The value must be a positive number. The default position is on the right edge of the list. You can adjust the horizontal position of the scrollbar by setting this offset. If the scrollbar is drawn outside the list and the parent component of the list is capable of cropping, the scrollbar will be cropped.| -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

scrollTo

-

{ index: number(specified position) }

-

Scrolls the list to the position of the item at the specified index.

-

scrollBy

-

ScrollParam

-

Scrolls the list for a certain distance.

-

This method applies only to smart TVs.

-

scrollTop

-

{ smooth: boolean }

-

If smooth is set to false (default value), the list is directly scrolled to the top.

-

If smooth is set to true, the list is smoothly scrolled to the top.

-

scrollBottom

-

{ smooth: boolean }

-

If smooth is set to false (default value), the list is directly scrolled to the bottom.

-

If smooth is set to true, the list is smoothly scrolled to the bottom.

-

scrollPage

-

{ reverse: boolean, smooth: boolean }

-

If reverse is set to false (default value), the next page is displayed. If there is no next page, the list scrolls to the bottom.

-

If reverse is set to true, the previous page is displayed. If there is no previous page, the list scrolls to the top.

-

If smooth is set to false (default value), the list is directly scrolled to another page.

-

If smooth is set to true, the list is smoothly scrolled to another page.

-

scrollArrow

-

{ reverse: boolean, smooth: boolean }

-

If reverse is set to false (default value), the list scrolls towards the bottom for a certain distance. If there is no sufficient distance, the list scrolls to the bottom.

-

If reverse is set to true, the list scrolls towards the top for a certain distance. If there is no sufficient distance, the list scrolls to the top.

-

If smooth is set to false (default value), the list is directly scrolled.

-

If smooth is set to true, the list is smoothly scrolled.

-

collapseGroup

-

{ groupid: string }

-

Collapses a group.

-

groupid: ID of the group to collapse.

-

All groups are collapsed when groupid is not specified.

-

expandGroup

-

{ groupid: string }

-

Expands a group.

-

groupid: ID of the group to expand.

-

All groups are expanded when groupid is not specified.

-

currentOffset

-

-

-

Returns the offset of the current scrolling. The return value type is Object. For details, see Table 2.

-
+## Events -**Table 1** ScrollParam +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Default Value

-

Remarks

-

dx

-

number

-

No

-

0

-

Offset for scrolling the list in the horizontal direction, in px.

-

dy

-

number

-

No

-

0

-

Offset for scrolling the list in the vertical direction, in px.

-

smooth

-

boolean

-

No

-

true

-

Whether a sliding animation is displayed when the list position is changed.

-
+| Name | Parameter | Description | +| -------------------------- | ---------------------------------------- | ---------------------------------------- | +| indexerchange5+ | { local: booleanValue } | Triggered when the indexer switches between local and alphabetic indexers. This parameter takes effect only when both **indexer** and **indexermulti** are set to **true**. The values of **booleanValue** can be:
- **true**: The local index is displayed.
- **false**: The alphabetic index is displayed.| +| scroll | { scrollX: scrollXValue, scrollY: scrollYValue, scrollState: stateValue } | Triggered to indicate the offset and status of list scrolling.
**stateValue: 0**: The list is not scrolling.
**stateValue: 1**: The list is scrolling along with user's touches.
**stateValue: 2**: The list is scrolling after the touches stop.| +| scrollbottom | - | Triggered when the list is scrolled to the bottom. | +| scrolltop | - | Triggered when the list is scrolled to the top. | +| scrollend | - | Triggered when the list stops scrolling. | +| scrolltouchup | - | Triggered when the list continues scrolling after the user lifts their fingers. | +| requestitem | - | Triggered for a request to create a list-item.
This event is triggered when the number of cached list-items outside the visible area is less than the value of **cachedcount** during long list loading with delay.| +| rotate7+ | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. | -**Table 2** Attributes of the currentOffset return object - - - - - - - - - - - - - - - -

Name

-

Type

-

Remarks

-

x

-

number

-

Scrolling offset in the x-axis, in px

-

y

-

number

-

Scrolling offset in the y-axis, in px

-
+## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ------------- | ---------------------------------------- | ---------------------------------------- | +| scrollTo | { index: number(specified position) } | Scrolls the list to the position of the item at the specified index. | +| scrollTop | { smooth: boolean } | If **smooth** is set to **false** (default value), the list is directly scrolled to the top.
If **smooth** is set to **true**, the list is smoothly scrolled to the top.| +| scrollBottom | { smooth: boolean } | If **smooth** is set to **false** (default value), the list is directly scrolled to the bottom.
If **smooth** is set to **true**, the list is smoothly scrolled to the bottom.| +| scrollPage | { reverse: boolean, smooth: boolean } | If **reverse** is set to **false** (default value), the next page is displayed. If there is no next page, the list scrolls to the bottom.
If **reverse** is set to **true**, the previous page is displayed. If there is no previous page, the list scrolls to the top.
If **smooth** is set to **false** (default value), the list is directly scrolled to another page.
If **smooth** is set to **true**, the list is smoothly scrolled to another page.| +| scrollArrow | { reverse: boolean, smooth: boolean } | If **reverse** is set to **false** (default value), the list scrolls towards the bottom for a certain distance. If there is no sufficient distance, the list scrolls to the bottom.
If **reverse** is set to **true**, the list scrolls towards the top for a certain distance. If there is no sufficient distance, the list scrolls to the top.
If **smooth** is set to **false** (default value), the list is directly scrolled.
If **smooth** is set to **true**, the list is smoothly scrolled.| +| collapseGroup | { groupid: string } | Collapses a group.
**groupid**: ID of the group to collapse.
All groups are collapsed when **groupid** is not specified.| +| expandGroup | { groupid: string } | Expands a group.
**groupid**: ID of the group to expand.
All groups are expanded when **groupid** is not specified.| +| currentOffset | - | Returns the offset of the current scrolling. The return value type is Object. For details, see **currentOffset**.| + +**Table 1** currentOffset + +| Name | Type | Remarks | +| ---- | ------ | ---------------- | +| x | number | Scrolling offset in the x-axis, in px| +| y | number | Scrolling offset in the y-axis, in px| ## Example -``` +```html
@@ -638,7 +113,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.
``` -``` +```js // index.js export default { data: { @@ -653,7 +128,7 @@ export default { } ``` -``` +```css /* index.css */ .container { display: flex; @@ -678,4 +153,4 @@ export default { } ``` -![en-us_image_0000001185033226](figures/en-us_image_0000001185033226.png) \ No newline at end of file +![en-us_image_0000001185033226](figures/en-us_image_0000001185033226.png) diff --git a/en/application-dev/reference/arkui-js/js-components-container-panel.md b/en/application-dev/reference/arkui-js/js-components-container-panel.md index 6d45f57ae91364b353ffbf8874aee8027b36a297..89e23df188c5250d071bfdcf38b30c6af09e1863 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-panel.md +++ b/en/application-dev/reference/arkui-js/js-components-container-panel.md @@ -1,463 +1,89 @@ -# panel +# panel -The **** component is a slidable panel. It provides a lightweight content display window with flexible sizes. The **** component pops up when it is displayed. +> **NOTE** +> +> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. -## Child Components +The **\** component is a slidable, pop-up component that provides a lightweight content display window with flexible sizes. -Yes -## Attributes +## Child Components -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +Supported - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Triggered when

-

type

-

string

-

foldable

-

Yes

-

Type of the slidable panel. This attribute cannot be dynamically changed. Available values are as follows:

-
  • minibar: A minibar panel displays content in the minibar area or a large (fullscreen-like) area.

    -
  • foldable: A foldable panel displays permanent content in a large (fullscreen-like), medium-sized (halfscreen-like), or small area.

    -
  • temporary: A temporary panel displays content in a large (fullscreen-like) or medium-sized (halfscreen-like) area.

    -
-

mode

-

string

-

full

-

No

-

Initial status of the slidable panel. Available values are as follows:

-
  1. mini: Displays a minibar or foldable panel in its minimum size. This attribute does not take effect for temporary panels.

    -
  2. half: Displays a foldable or temporary panel in a medium-sized (halfscreen-like) area. This attribute does not take effect for minibar panels.

    -
  3. full: Displays a panel in a large (fullscreen-like) area.

    -
-

dragbar

-

boolean

-

true

-

No

-

Whether to enable a drag bar. The value true indicates that the drag bar will be displayed, and false indicates the opposite.

-

fullheight

-

<length>

-

-

-

No

-

Panel height in the full mode. The default value is the screen height minus 8 px.

-

halfheight

-

<length>

-

-

-

No

-

Panel height in the half mode. The default value is half of the screen height.

-

miniheight

-

<length>

-

-

-

No

-

Panel height in the mini mode. The default value is 48px.

-
->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- Rendering attributes, including **for**, **if**, and **show**, are not supported. ->- The **focusable** and **disabled** attributes are not supported. +## Attributes -## Styles +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -Only the following style attributes are supported. +| Name | Type | Default Value | Mandatory | Description | +| ---------- | -------------- | -------- | ---- | ---------------------------------------- | +| type | string | foldable | Yes | Type of the slidable panel. This attribute cannot be dynamically changed. Available values are as follows:
- **minibar**: A minibar panel displays content in the minibar area or a large (fullscreen-like) area.
- **foldable**: A foldable panel displays permanent content in a large (fullscreen-like), medium-sized (halfscreen-like), or small area.
- **temporary**: A temporary panel displays content in a large (fullscreen-like) or medium-sized (halfscreen-like) area.| +| mode | string | full | No | Initial status of the slidable panel. Available values are as follows:
1. **mini**: Displays a **minibar** or **foldable** panel in its minimum size. This attribute does not take effect for **temporary** panels.
2. **half**: Displays a **foldable** or **temporary** panel in a medium-sized (halfscreen-like) area. This attribute does not take effect for **minibar** panels.
3. **full**: Displays a panel in a large (fullscreen-like) area.| +| dragbar | boolean | true | No | Whether to enable a drag bar. The value **true** means that the drag bar will be displayed, and **false** means the opposite. | +| fullheight | <length> | - | No | Panel height in the **full** mode. The default value is the screen height minus 8 px. | +| halfheight | <length> | - | No | Panel height in the **half** mode. The default value is half of the screen height. | +| miniheight | <length> | - | No | Panel height in the **mini** mode. The default value is **48px**. | + +> **NOTE** +> - Rendering attributes, including **for**, **if**, and **show**, are not supported. +> +> - The **focusable** and **disabled** attributes are not supported. + + +## Styles + +Only the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---------------------------------------- | ---------------------------------------- | ------------ | ---- | ---------------------------------------- | +| padding | <length> | 0 | No | The attribute can have one to four values:
- If you set only one value, it specifies the padding for all the four sides.
- If you set two values, the first value specifies the top and bottom padding, and the second value specifies the left and right padding.
- If you set three values, the first value specifies the top padding, the second value specifies the left and right padding, and the third value specifies the bottom padding.
- If you set four values, they respectively specify the padding for top, right, bottom, and left sides (in clockwise order).| +| padding-[left\|top\|right\|bottom] | <length> | 0 | No | Left, top, right, and bottom padding. | +| padding-[start\|end] | <length> | 0 | No | Start and end padding. | +| margin | <length> | 0 | No | Shorthand attribute to set the margin for all sides in a declaration. The attribute can have one to four values:
- If you set only one value, it specifies the margin for all the four sides.
- If you set two values, the first value specifies the top and bottom margins, and the second value specifies the left and right margins.
- If you set three values, the first value specifies the top margin, the second value specifies the left and right margins, and the third value specifies the bottom margin.
- If you set four values, they respectively specify the margin for top, right, bottom, and left sides (in clockwise order).| +| margin-[left\|top\|right\|bottom] | <length> | 0 | No | Left, top, right, and bottom margins. | +| margin-[start\|end] | <length> | 0 | No | Start and end margins. | +| border | - | 0 | No | Shorthand attribute to set all borders. Set **border-width**, **border-style**, and **border-color** in sequence. Default values are used for attributes that are not set.| +| border-style | string | solid | No | Shorthand attribute to set the style for all borders. Available values are as follows:
- **dotted**: dotted border. The radius of a dot is half of **border-width**.
- **dashed**: dashed border.
- **solid**: solid border.| +| border-[left\|top\|right\|bottom]-style | string | solid | No | Styles of the left, top, right, and bottom borders. The available values are **dotted**, **dashed**, and **solid**.| +| border-[left\|top\|right\|bottom] | - | - | No | Shorthand attribute to set the borders for every side respectively. Set **border-width**, **border-style**, and **border-color** in sequence. Default values are used for attributes that are not set.| +| border-width | <length> | 0 | No | Shorthand attribute to set the width for all borders, or separately set the width for each border. | +| border-[left\|top\|right\|bottom]-width | <length> | 0 | No | Attribute to set widths of left, top, right, and bottom borders. | +| border-color | <color> | black | No | Shorthand attribute to set the color for all borders, or separately set the color for each border. | +| border-[left\|top\|right\|bottom]-color | <color> | black | No | Attribute to set colors for left, top, right, and bottom borders. | +| border-radius | <length> | - | No | Attribute to set the radius of round-corner borders. This attribute cannot be used to set the width or color of a specific border. To set the width or color, you must set **border-width** or **border-color** for all the borders at the same time. | +| border-[top\|bottom]-[left\|right]-radius | <length> | - | No | Attribute to respectively set the radii of upper-left, upper-right, lower-right, and lower-left rounded corners | +| background | <linear-gradient> | - | No | Background. This attribute supports [gradient styles](../arkui-js/js-components-common-gradient.md) only and is not compatible with **background-color** or **background-image**.| +| background-color | <color> | - | No | Background color. | +| background-image | string | - | No | Background image. This attribute is not compatible with **background-color** or **background**. Local image resources are supported. | +| background-size | - string
- <length> <length>
- <percentage> <percentage> | auto | No | Background image size.
- The **string** values are as follows:
- **contain**: Expands the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: Extends the background image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: Retains the original aspect ratio of the image.
- The two **length** values are width and height of the background image. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
- The two **percentage** values are width and height of the background image in percentage of the parent element. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default. | +| background-repeat | string | repeat | No | Repeating attribute of a background image. By default, a background image is repeated both horizontally and vertically.
- **repeat**: The image is repeated along the x-axis and y-axis at the same time.
- **repeat-x**: The image is repeated along the x-axis.
- **repeat-y**: The image is repeated along the y-axis.
- **no-repeat**: The image is not repeated.| +| background-position | - string string
- <length> <length>
- <percentage> <percentage> | 0px 0px | No | - Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.
- **left**: leftmost in the horizontal direction.
- **right**: rightmost in the horizontal direction.
- **top**: top in the vertical direction.
- **bottom**: bottom in the vertical direction.
- **center**: center position.
- Using **length** values: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is **0 0**. The unit is pixel. If only one value is specified, the other one is **50%**.
- Using **percentage** values: The first value indicates the horizontal position, and the second value indicates the vertical position. **0% 0%** indicates the upper left corner. **100% 100%** indicates the lower right corner. If only one value is specified, the other one is **50%**.
- Using both **percentage** and **length** values.| +| opacity | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Triggered when

-

padding

-

<length>

-

0

-

No

-
The attribute can have one to four values:
  • If you set only one value, it specifies the padding for four sides.

    -
  • If you set two values, the first value specifies the top and bottom padding, and the second value specifies the left and right padding.

    -
  • If you set three values, the first value specifies the top padding, the second value specifies the left and right padding, and the third value specifies the bottom padding.

    -
  • If you set four values, they respectively specify the padding for top, right, bottom, and left sides (in clockwise order).

    -
-
-

padding-[left|top|right|bottom]

-

<length>

-

0

-

No

-

Left, top, right, and bottom padding.

-

padding-[start|end]

-

<length>

-

0

-

No

-

Start and end padding.

-

margin

-

<length>

-

0

-

No

-

Shorthand attribute to set margins for all sides in a declaration. The attribute can have one to four values:

-
  • If you set only one value, it specifies the margin for all the four sides.

    -
  • If you set two values, the first value is for the top and bottom sides and the second value for the left and right sides.

    -
  • If you set three values, the first value is for the top, the second value for the left and right, and the third value for the bottom.

    -
  • If you set four values, they are margins for top, right, bottom, and left sides, respectively.

    -
-

margin-[left|top|right|bottom]

-

<length>

-

0

-

No

-

Left, top, right, and bottom margins.

-

margin-[start|end]

-

<length>

-

0

-

No

-

Start and end margins.

-

border

-

-

-

0

-

No

-

Shorthand attribute to set all borders. Set border-width, border-style, and border-color in sequence. Default values are used for attributes that are not set.

-

border-style

-

string

-

solid

-

No

-

Shorthand attribute to set the style for all borders. Available values are as follows:

-
  • dotted: dotted border. The radius of a dot is half of border-width.
  • dashed: dashed border
-
  • solid: solid border
-

border-[left|top|right|bottom]-style

-

string

-

solid

-

No

-

Styles of the left, top, right, and bottom borders. The available values are dotted, dashed, and solid.

-

border-[left|top|right|bottom]

-

-

-

-

-

No

-

Shorthand attribute to set the borders for every side respectively. You set border-width, border-style, and border-color in sequence. Default values are used for attributes that are not set.

-

border-width

-

<length>

-

0

-

No

-

Shorthand attribute to set the width of all borders, or separately set the width of each border.

-

border-[left|top|right|bottom]-width

-

<length>

-

0

-

No

-

Attribute to set widths of left, top, right, and bottom borders.

-

border-color

-

<color>

-

black

-

No

-

Shorthand attribute to set the color of all borders, or separately set the color of each border.

-

border-[left|top|right|bottom]-color

-

<color>

-

black

-

No

-

Attribute to set colors of left, top, right, and bottom borders.

-

border-radius

-

<length>

-

-

-

No

-

Attribute to set the radius of round-corner borders. This attribute cannot be used to set the width or color of a specific border. To set the width or color, you need to set border-width or border-color for all the borders at the same time.

-

border-[top|bottom]-[left|right]-radius

-

<length>

-

-

-

No

-

Attribute to receptively set the radii of upper-left, upper-right, lower-right, and lower-left rounded corners

-

background

-

<linear-gradient>

-

-

-

No

-

This attribute supports Gradient Styles only but is not compatible with background-color or background-image.

-

background-color

-

<color>

-

-

-

No

-

Background color.

-

background-image

-

string

-

-

-

No

-

Background image. Currently, this attribute is not compatible with background-color or background. Local image resources are supported.

-

background-size

-
  • string
  • <length> <length>
  • <percentage> <percentage>
-

auto

-

No

-

Background image size.

-
  • The string values are as follows:
    • contain: Expands the image to the maximum size so that the height and width of the image are applicable to the content area.
    • cover: Extends the background image to a large enough size so that the background image completely covers the background area. Some parts of the image may not be displayed in the background area.
    • auto: The original image width-height ratio is retained.
    -
  • The two <length> values are as follows:

    Width and height of the background image. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to auto by default.

    -
  • The two <percentage> values are as follows:

    Width and height of the background image in percentage of the parent element. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to auto by default.

    -
-

background-repeat

-

string

-

repeat

-

No

-

Repeating attribute of a background image. By default, a background image is repeated both horizontally and vertically.

-
  • repeat: Repeatedly draws images along the x-axis and y-axis at the same time.
  • repeat-x: Repeatedly draws images along the x-axis.
  • repeat-y: Repeatedly draws images along the y-axis.
  • no-repeat: The image is not drawn repeatedly.
-

background-position

-
  • string string
  • <length> <length>
  • <percentage> <percentage>
-

0px 0px

-

No

-
  • Using keywords: If only one keyword is specified, the other value is center by default. The two values define the horizontal position and vertical position, respectively.
    • left: leftmost in the horizontal direction
    • right: rightmost in the horizontal direction
    • top: top in the vertical direction
    • bottom: bottom in the vertical direction
    • center: center position
    -
-
  • Using <length>: The first value indicates the horizontal position, and the second value indicates the vertical position. 0 0 indicates the upper left corner. The unit is pixel. If only one value is specified, the other one is 50%.
  • Using <percentage>: The first value indicates the horizontal position, and the second value indicates the vertical position. 0% 0% indicates the upper left corner. 100% 100% indicates the lower right corner. If only one value is specified, the other one is 50%.
  • Using both <percentage> and <length>.
-

opacity

-

number

-

1

-

No

-

Opacity of an element. The value ranges from 0 to 1. The value 1 means opaque, and 0 means completely transparent.

-
-## Events +## Events The following events are supported. - - - - - - - - - - - -

Name

-

Parameter

-

Triggered when

-

sizechange

-

{ size: { height: heightLength, width: widthLength }, mode: modeStr }

-

Triggered when the status of the slidable panel changes. Available mode values are as follows:

-
  1. mini: Displays a minibar or foldable panel in its minimum size.

    -
  2. half: Displays a foldable panel in a medium-sized (halfscreen-like) area.

    -
  3. full: Displays a panel in a large (fullscreen-like) area.

    -
    NOTE:

    The returned height value indicates the content area height. However, when the dragbar attribute is true, the height value is the height of the drag bar plus that of the content area.

    -
    -
-
+| Name | Parameter | Description | +| ---------- | ---------------------------------------- | ---------------------------------------- | +| sizechange | { size: { height: heightLength, width: widthLength }, mode: modeStr } | Triggered when the status of the slidable panel changes. Available **mode** values are as follows:
- **mini**: Displays a **minibar** or **foldable** panel in its minimum size.
- **half**: Displays a **foldable** panel in a medium-sized (halfscreen-like) area.
- **full**: Displays a panel in a large (fullscreen-like) area.
The returned **height** value indicates the content area height. However, when the **dragbar** attribute is **true**, the **height** value is the height of the drag bar plus that of the content area.| -## Methods -Only the following methods are supported. +## Methods - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Triggered when

-

show

-

-

-

Pops the slidable panel up.

-

close

-

-

-

Closes the slidable panel that has been popped up.

-
+The following methods are supported. -## Example +| Name | Parameter | Description | +| ----- | ---- | ------------- | +| show | - | Pops the slidable panel up.| +| close | - | Closes the slidable panel that has been popped up.| -``` + +## Example + +```html
@@ -476,7 +102,7 @@ Only the following methods are supported.
``` -``` +```css /* xxx.css */ .doc-page { flex-direction: column; @@ -515,7 +141,7 @@ Only the following methods are supported. } ``` -``` +```js // xxx.js export default { data: { @@ -533,5 +159,4 @@ export default { } ``` -![](figures/panel6.gif) - +![panel6](figures/panel6.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-popup.md b/en/application-dev/reference/arkui-js/js-components-container-popup.md index dc2baeeb728ab71e6662ef5ca87c35b8465a5560..ef1cf3c658d395c64808eb9a1743c8d67b76bd81 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-popup.md +++ b/en/application-dev/reference/arkui-js/js-components-container-popup.md @@ -1,192 +1,82 @@ -# popup +# popup -The **** component is used to display a pop-up to offer instructions after a user clicks a bound control. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +Bubble indication. The **\** component is used to display a pop-up to offer instructions after a user clicks a bound control. + +## Required Permissions None -## Child Components - -All child components are supported. Each **** can have only one child component5+. - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

target

-

string

-

-

-

Yes

-

ID of the target element. Dynamic switch is not supported.

-

placement

-

string

-

bottom

-

No

-

Position of the pop-up. Available values are as follows:

-
  • left: The pop-up is displayed on the left of the target item.
  • right: The pop-up is displayed on the right of the target item.
  • top: The pop-up is displayed at the top of the target item.
  • bottom: The pop-up is displayed at the bottom of the target item.
  • topLeft: The pop-up is displayed on the upper left of the target item.
  • topRight: The pop-up is displayed on the upper right of the target item.
  • bottomLeft: The pop-up is displayed on the bottom left of the target item.
  • bottomRight: The pop-up is displayed on the bottom right of the target item.
-

keepalive5+

-

boolean

-

false

-

No

-

Whether to retain this pop-up.

-

true: The pop-up does not disappear when users tap other areas or switch the page. To hide the pop-up, you need to call the hide method.

-

false: The pop-up disappears when users tap other areas or switch the page.

-

clickable5+

-

boolean

-

true

-

No

-

Whether to display the pop-up when users click the bound control. If this parameter is set to false, the pop-up can be triggered only by a method call.

-

arrowoffset5+

-

<length>

-

0

-

No

-

Offset of the pop-up arrow. By default, the arrow is centered. A positive value means that the arrow moves along the language direction (LTR or RTL), and a negative value means that the arrow moves along the opposite direction of the language direction.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- The **focusable** attribute is not supported. - -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

mask-color

-

<color>

-

-

-

No

-

Color configuration of the mask layer. By default, the mask layer is completely transparent.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- Position-related styles are not supported. - -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - - - - - - - - - - - -

Name

-

Parameters

-

Description

-

visibilitychange

-

{ visibility: boolean }

-

Triggered when a pop-up appears or disappears.

-
- -## Methods - -Only the following methods are supported. - - - - - - - - - - - - - - - - -

Name

-

Parameters

-

Description

-

show5+

-

-

-

Pops up a message.

-

hide5+

-

-

-

Hides a pop-up.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->1. Attributes and styles of a **** component cannot be dynamically updated. ->2. Margins of a pop-up take effect depending on its position relative to the target element. For example, if the pop-up is below the target element, only **margin-top** takes effect; if the pop-up displays on the upper left of the target element, only **margin-bottom** and **margin-right** take effect. ->3. Styles set for the four borders of a pop-up must be the same. If they are different and the border radius is **0**, the first configured border style \(in the sequence of left, top, right, and bottom\) takes effect. Otherwise, the **border** attribute does not take effect. ->4. The click event bound to the target element of a pop-up does not take effect. - -## Example Code -``` +## Child Components + +This component supports only one child component.5+ + + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| target | string | - | Yes| ID of the target element. Dynamic switch is not supported.| +| placement | string | bottom | No| Position of the pop-up. Available values are as follows:
- **left**: The pop-up is displayed on the left of the target item.
- **right**: The pop-up is displayed on the right of the target item.
- **top**: The pop-up is displayed at the top of the target item.
- **bottom**: The pop-up is displayed at the bottom of the target item.
- **topLeft**: The pop-up is displayed on the upper left of the target item.
- **topRight**: The pop-up is displayed on the upper right of the target item.
- **bottomLeft**: The pop-up is displayed on the bottom left of the target item.
- **bottomRight**: The pop-up is displayed on the bottom right of the target item.| +| keepalive5+ | boolean | false | No| Whether to retain this pop-up. **true**: The pop-up does not disappear when users tap other areas or switch the page. To hide the pop-up, call the **hide** method.
**false**: The pop-up disappears when users tap other areas or switch the page.| +| clickable5+ | boolean | true | No| Whether to display the pop-up when users click the bound control. If this parameter is set to **false**, the pop-up can be triggered only by a method call.| +| arrowoffset5+ | <length> | 0 | No| Offset of the pop-up arrow. By default, the arrow is centered. A positive value means that the arrow moves along the language direction (LTR or RTL), and a negative value means that the arrow moves along the opposite direction of the language direction.| + +> **NOTE** +> +> The **focusable** attribute is not supported. + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| mask-color | <color> | - | No| Color configuration of the mask layer. By default, the mask layer is completely transparent.| + +> **NOTE** +> +> Position-related styles are not supported. + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +| Name| Parameter| Description| +| -------- | -------- | -------- | +| visibilitychange | { visibility: boolean } | Triggered when a pop-up appears or disappears.| + + +## Methods + +The following methods are supported. + +| Name| Parameter| Description| +| -------- | -------- | -------- | +| show5+ | - | Shows the pop-up.| +| hide5+ | - | Hides the pop-up.| + +> **NOTE** +> 1. Attributes and styles of a **\** component cannot be dynamically updated. +> +> 2. Margins of a pop-up take effect depending on its position relative to the target element. For example, if the pop-up is below the target element, only **margin-top** takes effect; if the pop-up displays on the upper left of the target element, only **margin-bottom** and **margin-right** take effect. +> +> 3. Styles set for the four borders of a pop-up must be the same. If they are different and the border radius is **0**, the first configured border style (in the sequence of left, top, right, and bottom) takes effect. Otherwise, the **border** attribute does not take effect. +> +> 4. The click event bound to the target element of a pop-up does not take effect. + + +## Example + +```html
Click to show the pop-up @@ -199,7 +89,7 @@ Only the following methods are supported.
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -219,7 +109,7 @@ Only the following methods are supported. } ``` -``` +```js // xxx.js import prompt from '@system.prompt' export default { @@ -238,5 +128,4 @@ export default { } ``` -![](figures/en-us_image_0000001178886129.png) - +![en-us_image_0000001178886129](figures/en-us_image_0000001178886129.png) diff --git a/en/application-dev/reference/arkui-js/js-components-container-refresh.md b/en/application-dev/reference/arkui-js/js-components-container-refresh.md index 1332c9257080ca1a0da9397582f22b56ee7f701f..8c3d8c5f42dfeb9721e0c00b1b7a7dbb31187241 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-refresh.md +++ b/en/application-dev/reference/arkui-js/js-components-container-refresh.md @@ -1,185 +1,63 @@ -# refresh +# refresh -The **** component is used to pull down to refresh the page. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **** component is used to refresh a page through a pull-down gesture. + +## Required Permissions None -## Child Components + +## Child Components Supported -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

offset

-

<length>

-

-

-

No

-

Distance to the top of the parent component from the <refresh> component that comes to rest after a successful swipe gesture.

-

refreshing

-

boolean

-

false

-

No

-

Whether the <refresh> component is being used for refreshing.

-

type

-

string

-

auto

-

No

-

Dynamic effect when the component is refreshed. Two options are available and cannot be modified dynamically.

-
  • auto: default effect. When the list is pulled to the top, the list does not move. When the list is pulled to the bottom, a circle is displayed.
  • pulldown: When the list is pulled to the top, users can continue to pull down to trigger a refresh. The rebound effect will appear after the refresh. If the child component contains a list, set scrolleffect of the list to no to prevent drop-down effect conflicts.
-

lasttime

-

boolean

-

false

-

No

-

Whether to display the last update time. The character string format is last update time: XXXX, where XXXX is displayed based on the time and date display specifications and cannot be dynamically modified. (It is recommended that this attribute be used when type is set to pulldown. The fixed distance is at the bottom of the content drop-down area. Pay attention to the offset attribute setting to prevent overlapping.)

-

timeoffset6+

-

<length>

-

-

-

No

-

Sets the distance between the update time and the top of the parent component.

-

friction

-

number

-

42

-

No

-

Pull-down friction coefficient. The value ranges from 0 to 100. A larger value indicates a more responsive component. For example, if a user pulls the component down 100 px, it will actually move 100 * friction% px.

-
NOTE:

-
-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

background-color

-

<color>

-

white

-

No

-

Background color of the <refresh> component.

-

progress-color

-

<color>

-

black

-

No

-

Loading color of the <refresh> component.

-
- -## Events + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| offset | <length> | - | No| Distance to the top of the parent component from the **** component that comes to rest after a successful pull-down gesture.| +| refreshing | boolean | false | No| Whether the **\** component is being used for refreshing.| +| type | string | auto | No| Dynamic effect when the component is refreshed. Two options are available and cannot be modified dynamically.
- **auto**: default effect. When the list is pulled to the top, the list does not move. When the list is pulled to the bottom, a circle is displayed.
- **pulldown**: When the list is pulled to the top, users can continue to pull down to trigger a refresh. The rebound effect will appear after the refresh. If the child component contains a list, set **scrolleffect** of the list to **no** to prevent drop-down effect conflicts.| +| lasttime | boolean | false | No| Whether to display the last update time. The character string format is **last update time: XXXX**, where **XXXX** is displayed based on the certain time and date formats and cannot be dynamically modified. (It is recommended that this attribute be used when **type** is set to **pulldown**. The fixed distance is at the bottom of the content drop-down area. Pay attention to the **offset** attribute setting to prevent overlapping.)| +| timeoffset6+ | <length> | - | No| Distance between the update time and the top of the parent component.| +| friction | number | 42 | No| Pull-down friction coefficient. The value ranges from 0 to 100. A larger value indicates a more responsive component. For example, if a user pulls the component down 100 px, it will actually move 100 * **friction**% px.| + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| background-color | <color> | white | No| Background color of the **\** component.| +| progress-color | <color> | black | No| Loading color of the **\** component.| + + +## Events The following events are supported. - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

refresh

-

{ refreshing: refreshingValue }

-

Triggered when the <refresh> component is pulled down and the refresh status changes. Available values are as follows:

-
  • false: The <refresh> component is being pulled down.
  • true: The <refresh> component is not being pulled down.
-

pulldown

-

{ state: string }

-

Triggered when a user starts or stops pulling down the <refresh> component. Available values are as follows:

-
  • start: The pull-down starts.
  • end: The pull-down ends.
-
- -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are not supported. - -## Example +| Name| Parameter| Description| +| -------- | -------- | -------- | +| refresh | { refreshing: refreshingValue } | Triggered when the **\** component is pulled down and the refresh status changes. Available values are as follows:
- **false**: The **\** component is being pulled down.
- **true**: The **\** component is not being pulled down.| +| pulldown | { state: string } | Triggered when a user starts or stops pulling down the **\** component. Available values are as follows:
- **start**: The pull-down starts.
- **end**: The pull-down ends.| -``` + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are not supported. + + +## Example + +```html
@@ -194,7 +72,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are not suppor
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -227,7 +105,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are not suppor } ``` -``` +```js // xxx.js import prompt from '@system.prompt'; export default { @@ -238,7 +116,7 @@ export default { onInit() { this.list = []; for (var i = 0; i <= 3; i++) { - var item ='List element' + i; + var item ='List element' + i; this.list.push(item); } }, @@ -260,5 +138,4 @@ export default { } ``` -![](figures/en-us_image_0000001150719520.gif) - +![en-us_image_0000001150719520](figures/en-us_image_0000001150719520.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-stack.md b/en/application-dev/reference/arkui-js/js-components-container-stack.md index af594dff35489a9a490560c71a4cc8097be15209..6041c884ed1da03a0aba1c6e524e1799517a02f6 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-stack.md +++ b/en/application-dev/reference/arkui-js/js-components-container-stack.md @@ -1,34 +1,43 @@ -# stack +# stack -The **** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one. + +## Required Permissions None -## Child Components + +## Child Components Supported -## Attributes -Attributes in [Universal Attributes](js-components-common-attributes.md) are supported. +## Attributes -## Styles +The [universal attributes](../arkui-js/js-components-common-attributes.md) are supported. -Styles in [Universal Styles](js-components-common-styles.md) are supported. -## Events +## Styles -Events in [Universal Events](js-components-common-events.md) are supported. +The [universal styles](../arkui-js/js-components-common-styles.md) are supported. -## Methods -Methods in [Universal Methods](js-components-common-methods.md) are supported. +## Events -## Example +The [universal events](../arkui-js/js-components-common-events.md) are supported. -``` +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +```html
@@ -37,7 +46,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported.
``` -``` +```css /* xxx.css */ .stack-parent { width: 400px; @@ -68,5 +77,4 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -![](figures/en-us_image_0000001127284958.png) - +![en-us_image_0000001127284958](figures/en-us_image_0000001127284958.png) diff --git a/en/application-dev/reference/arkui-js/js-components-container-stepper.md b/en/application-dev/reference/arkui-js/js-components-container-stepper.md index fd10e69fdcef5a82075c4f9fd8d8cc3943a9763c..6a666a454cd424e1b3daf67fcae1c4a4e08f67a6 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-stepper.md +++ b/en/application-dev/reference/arkui-js/js-components-container-stepper.md @@ -1,11 +1,11 @@ # stepper -The **\** component provides a step navigator. When multiple steps are required to complete a task, you can use the **\** component to navigate your users through the whole process. - > **NOTE** > > This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component provides a step navigator. When multiple steps are required to complete a task, you can use the **\** component to navigate your users through the whole process. + ## Required Permissions @@ -27,7 +27,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Description | | ----- | ------ | ---- | ------------------------------ | -| index | number | - | Index of the **** child component that is currently displayed.| +| index | number | - | Index of the **\** child component that is currently displayed.| ## Styles @@ -48,8 +48,8 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md | finish | - | Triggered when the last step on the navigator is complete. | | skip | - | Triggered when users click the skip button, which works only if you have called **setNextButtonStatus** method to allow users to skip all steps.| | change | { prevIndex: prevIndex, index: index} | Triggered when users click the left or right (text) button of the step navigator to switch between steps. **prevIndex** indicates the index of the previous step, and **index** indicates that of the current step.| -| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **** child component as the next step to go.| -| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **** child component as the previous step.| +| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\** child component as the next step to go.| +| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\** child component as the previous step.| ## Methods @@ -98,6 +98,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. height: 300px; } .stepperItem { + width: 100%; flex-direction: column; align-items: center; } diff --git a/en/application-dev/reference/arkui-js/js-components-container-swiper.md b/en/application-dev/reference/arkui-js/js-components-container-swiper.md index 2070bfb323bd72c43c663601c5bf74435565728e..7ef9f5da631cfe71fddde0a1d1f5f16b0e722560 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-swiper.md +++ b/en/application-dev/reference/arkui-js/js-components-container-swiper.md @@ -1,324 +1,78 @@ -# swiper +# swiper -The **** component provides a container that allows users to switch among child components by swiping operations. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component provides a container that allows users to switch among child components using swipe gestures. + +## Required Permissions None -## Child Components -All child components except **** are supported. +## Child Components -## Attributes +Supported -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

index

-

number

-

0

-

No

-

Index of a child component currently displayed in the container.

-

autoplay

-

boolean

-

false

-

No

-

Whether to enable autoplay for child component switching. If this attribute is true, the indicator does not take effect5+.

-

interval

-

number

-

3000

-

No

-

Autoplay interval, in milliseconds, when autoplay is enabled.

-

indicator

-

boolean

-

true

-

No

-

Whether to enable the indicator. The default value is true.

-

digital5+

-

boolean

-

false

-

No

-

Whether to enable the digital indicator. The default value is false.

-
NOTE:

The digital indicator takes effect only when indicator is set to true.

-
-

indicatordisabled5+

-

boolean

-

false

-

No

-

Whether gesture operations are disabled on the indicator. If this attribute is set to true, the indicator does not respond to clicking or dragging operations.

-

loop

-

boolean

-

true

-

No

-

Whether to enable looping.

-

duration

-

number

-

-

-

No

-

Duration of the autoplay for child component switching.

-

vertical

-

boolean

-

false

-

No

-

Whether the swipe gesture is performed vertically. A vertical swipe uses the vertical indicator.

-

cachedsize7+

-

number

-

-1

-

No

-

Minimum number of cached items during delayed loading of the <swiper> component. The value -1 indicates that all content is cached.

-

scrolleffect7+

-

string

-

spring

-

No

-

Scroll effect. The options are as follows:

-
  • spring: Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded.
  • fade: Similar to the physical dynamic effect of fade. When you scroll to the edge, a wave shape fades. The fade changes according to the speed and scrolling distance.
  • none: No effect after the scroll bar is moved to the edge.
    NOTE:

    This attribute is valid only when loop is set to false.

    -
    -
-
+## Attributes -## Styles +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. +| Name | Type | Default Value | Mandatory | Description | +| ------------------------------ | ------- | ------ | ---- | ---------------------------------------- | +| index | number | 0 | No | Index of the child component currently displayed in the container. | +| autoplay | boolean | false | No | Whether to enable autoplay for child component switching. If this attribute is **true**, the indicator does not take effect5+. | +| interval | number | 3000 | No | Autoplay interval, in milliseconds, when autoplay is enabled. | +| indicator | boolean | true | No | Whether to enable the indicator. The default value is **true**. | +| digital5+ | boolean | false | No | Whether to enable the digital indicator. The default value is **false**.
The digital indicator takes effect only when **indicator** is set to **true**.| +| indicatordisabled5+ | boolean | false | No | Whether gesture operations are disabled on the indicator. If this attribute is set to **true**, the indicator does not respond to clicking or dragging operations. | +| loop | boolean | true | No | Whether to enable looping. | +| duration | number | - | No | Duration of the autoplay for child component switching. | +| vertical | boolean | false | No | Whether the swipe gesture is performed vertically. A vertical swipe uses the vertical indicator. | +| cachedsize7+ | number | -1 | No | Minimum number of cached items during delayed loading of the **\** component. The value **-1** indicates that all content is cached. | +| scrolleffect7+ | string | spring | No | Scroll effect. The options are as follows:
- **spring**: Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded.
- **fade**: Similar to the physical dynamic effect of fade. When you scroll to the edge, a wave shape fades. The fade changes according to the speed and scrolling distance.
- **none**: No effect after the scroll bar is moved to the edge.
This attribute is valid only when **loop** is set to **false**.| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

indicator-color

-

<color>

-

-

-

No

-

Fill color of the navigation point indicator.

-

indicator-selected-color

-

<color>

-

#ff007dff

-

No

-

Color of the currently selected navigation point indicator.

-

indicator-size

-

<length>

-

4px

-

No

-

Diameter of the navigation point indicator.

-

indicator-top|left|right|bottom

-

<length> | <percentage>

-

-

-

No

-

Relative position of the indicator in the swiper.

-

next-margin7+

-

<length> | <percentage>

-

-

-

No

-

Next margin, used to reveal a small part of the next item.

-

previous-margin7+

-

<length> | <percentage>

-

-

-

No

-

Previous margin, used to reveal a small part of the previous item.

-
-## Events +## Styles -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ index: currentIndex }

-

Triggered when the index of the currently displayed component changes.

-

rotation

-

{ value: rotationValue }

-

Triggered when the crown of the wearable rotates.

-

animationfinish7+

-

-

-

Triggered when the animation is finished.

-
+| Name | Type | Default Value | Mandatory | Description | +| ---------------------------------- | ---------------------------------------- | ---------- | ---- | -------------------- | +| indicator-color | <color> | - | No | Fill color of the indicator. | +| indicator-selected-color | <color> | \#ff007dff | No | Color of the currently selected indicator. | +| indicator-size | <length> | 4px | No | Diameter of the indicator. | +| indicator-top\|left\|right\|bottom | <length> \| <percentage> | - | No | Relative position of the indicator in the swiper.| +| next-margin7+ | <length> \| <percentage> | - | No | Next margin, used to reveal a small part of the next item. | +| previous-margin7+ | <length> \| <percentage> | - | No | Previous margin, used to reveal a small part of the previous item. | -## Methods -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. +## Events - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

swipeTo

-

{ index: number(specified position) }

-

Scrolls the child component to the position at the specified index.

-

showNext

-

None

-

Shows the next child component.

-

showPrevious

-

None

-

Shows the previous child component.

-
+In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. -## Example +| Name | Parameter | Description | +| ---------------------------- | --------------------------------------- | ------------------ | +| change | { index: currentIndex } | Triggered when the index of the currently displayed component changes.| +| rotation | { value: rotationValue } | Triggered when the crown of the wearable rotates. | +| animationfinish7+ | - | Triggered when the animation is finished. | -``` +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ------------ | -------------------------------------- | --------------- | +| swipeTo | { index: number(specified position) }| Scrolls the child component to the position at the specified index.| +| showNext | - | Shows the next child component. | +| showPrevious | - | Shows the previous child component. | + + +## Example + +```html
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -386,7 +140,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods. } ``` -``` +```js // xxx.js export default { swipeTo() { @@ -401,5 +155,4 @@ export default { } ``` -![](figures/4-0.gif) - +![4-0](figures/4-0.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-tab-bar.md b/en/application-dev/reference/arkui-js/js-components-container-tab-bar.md index da8e5ce58aedff5c24c26a444fd85a435c45b1ee..6d0dafcf6c7ea130f0cd6d3e2c281443a25e13c2 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-tab-bar.md +++ b/en/application-dev/reference/arkui-js/js-components-container-tab-bar.md @@ -1,60 +1,45 @@ -# tab-bar +# tab-bar -**** is a child component of **<[tabs](js-components-container-tabs.md)\>** and is used to provide the area to display tab labels. Its child components are horizontally arranged. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +**\** is a child component of **[\](js-components-container-tabs.md)** and is used to provide the area to display tab labels. Its child components are horizontally arranged. + +## Required Permissions None -## Child Components + +## Child Components Supported -## Attributes -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| mode | string | scrollable | No| Extensibility of the component width. Available values are as follows:
- **scrollable**: The width of a child component is the configured width. When the total width of all child components (including the margins) is greater than the tab-bar width, the child components can scroll horizontally.
- **fixed**: The width of a child component equals the tab-bar width divided by the number of child components.| + + +## Styles - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

mode

-

string

-

scrollable

-

No

-

Extensibility of the component width. Available values are as follows:

-
  • scrollable: The width of a child component is the configured width. When the total width of all child components (including the margins) is greater than the tab-bar width, the child components can scroll horizontally.
  • fixed: The width of a child component equals the tab-bar width divided by the number of child components.
-
+The [universal styles](../arkui-js/js-components-common-styles.md) are supported. -## Styles -Styles in [Universal Styles](js-components-common-styles.md) are supported. +## Events -## Events +The [universal events](../arkui-js/js-components-common-events.md) are supported. -Events in [Universal Events](js-components-common-events.md) are supported. -## Methods +## Methods -Methods in [Universal Methods](js-components-common-methods.md) are supported. +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. -## Example -For details, see the [tabs example code](js-components-container-tabs.md#section14993155318710). +## Example +For details, see [Example in tabs](../arkui-js/js-components-container-tabs.md#example). diff --git a/en/application-dev/reference/arkui-js/js-components-container-tabs.md b/en/application-dev/reference/arkui-js/js-components-container-tabs.md index 7e9c8e9a4ef41133cb7889eaf4e36a286145c152..27b3e4d01a03743fd33a443f1ece9690c394c26d 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-tabs.md +++ b/en/application-dev/reference/arkui-js/js-components-container-tabs.md @@ -1,90 +1,48 @@ -# tabs +# tabs -The **** component provides a tab container. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component provides a tab container. + +## Required Permissions None -## Child Components - -A **** can wrap at most one **<[tab-bar](js-components-container-tab-bar.md)\>** and at most one **<[tab-content](js-components-container-tab-content.md)\>**. - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

index

-

number

-

0

-

No

-

Index of the active tab.

-

vertical

-

boolean

-

false

-

No

-

Whether the tab is vertical. Available values are as follows:

-
  • false: The <tab-bar> and <tab-content> are arranged vertically.
  • true: The <tab-bar> and <tab-content> are arranged horizontally.
-
- -## Styles - -Styles in [Universal Styles](js-components-common-styles.md) are supported. - -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ index: indexValue }

-

Triggered upon tab switching.

-
NOTE:

This event is not triggered when the index value is dynamically changed.

-
-
- -## Example -``` +## Child Components + +A **\** component can wrap at most one **[\](../arkui-js/js-components-container-tab-bar.md)** and at most one **[\](../arkui-js/js-components-container-tab-content.md)**. + + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------- | ----- | ---- | ---------------------------------------- | +| index | number | 0 | No | Index of the active tab. | +| vertical | boolean | false | No | Whether the tab is vertical. Available values are as follows:
- **false**: The **\** and **\** are arranged vertically.
- **true**: The **\** and **\** are arranged horizontally.| + + +## Styles + +The [universal styles](../arkui-js/js-components-common-styles.md) are supported. + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +| Name | Parameter | Description | +| ------ | ------------------------------------ | ----------------------------- | +| change | { index: indexValue } | Triggered upon tab switching. This event is not triggered when the **index** value is dynamically changed.| + + +## Example + +```html
@@ -108,7 +66,7 @@ In addition to the events in [Universal Events](js-components-common-events.md)
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -142,7 +100,7 @@ In addition to the events in [Universal Events](js-components-common-events.md) } ``` -``` +```js // xxx.js export default { change: function(e) { @@ -151,5 +109,4 @@ export default { } ``` -![](figures/tab.gif) - +![tab](figures/tab.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md b/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md index 8ea11f6fb9fa1026c6e51ff87efddd8779f32d54..8ae629cba3025d8d6b6d9f3ea4597678a6c1d138 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md @@ -1,17 +1,16 @@ -# Basic Usage +# Basic Usage -Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can introduce a custom component to the host page through **element** as shown in the following code snippet: - -``` +Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can introduce a custom component to the host page through **element** as shown in the following code snippet: +```html
``` -The following is an example of using a custom component with **if-else**: -``` +The following is an example of using a custom component with **if-else**: +```html
@@ -20,46 +19,18 @@ The following is an example of using a custom component with **if-else**:
``` -- The **name** attribute indicates the custom component name \(optional\), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path \(mandatory\) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default. -- Event binding: Use **\(on|@\)**_child1_ syntax to bind a child component event to a custom component. In the child component, use **this.$emit\('**_child1_**', \{params:'**_parameter to pass_**'\}\)** for event triggering and value transferring. In the parent component, call **bindParentVmMethod** method and receive the parameters passed from the child component. - - >![](../../public_sys-resources/icon-note.gif) **NOTE:** - >For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **@children-event** instead of **childrenEvent**: **@children-event="bindParentVmMethod"**. +- The **name** attribute indicates the custom component name (optional), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path (mandatory) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default. -**Table 1** Objects +- Event binding: Use **(on|@)***child1* syntax to bind a child component event to a custom component. In the child component, use **this.$emit('***child1***', {params:'***parameter to pass***'})** for event triggering and value transferring. In the parent component, call **bindParentVmMethod** method and receive the parameters passed from the child component. + > **NOTE** + > + > For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **\@children-event** instead of **childrenEvent**: **\@children-event="bindParentVmMethod"**. - - - - - - - - - - - - - - - - - - - -

Attribute

-

Type

-

Description

-

data

-

Object/Function

-

Data model of the page. If the attribute is of the function type, the return value must be of the object type. The attribute name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (for, if, show, and tid).

-

Do not use this attribute and private or public at the same time. (Rich)

-

props

-

Array/Object

-

Used for communication between components. This attribute can be transferred to components via <tag xxxx='value'>. A props name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (for, if, show, and tid). Currently, props does not support functions.

-

computed

-

Object

-

Used for pre-processing an object for reading and setting. The result is cached. The name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words.

-
+**Table 1** Objects +| Name | Type | Description | +| -------- | --------------- | ---------------------------------------- | +| data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The attribute name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).
Do not use this attribute and **private** or **public** at the same time.(Rich) | +| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.| +| computed | Object | Used for pre-processing an object for reading and setting. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.| diff --git a/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md b/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md index b1b63b3e16d1e973c7a0854c29d84853f20806ea..55131eddc7e7613ae7fa58086ca5c59cc9ee35c9 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md @@ -1,40 +1,46 @@ -# Event Parameter +# Event Parameter A child component can also pass parameters to an upper-layer component through the bound event. The following example describes how to pass parameters through the custom event: -``` + +```html
- Click here to view the hidden text. - hello world + Click to View Hidden Text + hello world
``` -``` + +```js // comp.js export default { childClicked () { - this.$emit('eventType1', {text: 'Receive the parameters from the child component.'}); + this.$emit('eventType1', {text: 'Received parameters from the child component.'}); this.showObj = !this.showObj; }, } ``` -In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**: -``` +In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**: + + +```html +
Parent component: {{text}}
``` -``` + +```js // xxx.js export default { data: { - text: 'Start', + text: 'Start' }, textClicked (e) { this.text = e.detail.text; @@ -42,3 +48,4 @@ export default { } ``` +![EventParameters](figures/EventParameters.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-grid-col.md b/en/application-dev/reference/arkui-js/js-components-grid-col.md index 91bfc7498c4fec9a2e30b7829250766d5f5b080e..1e5de0a2098c526fb4bb7112a06c1115fede8a83 100644 --- a/en/application-dev/reference/arkui-js/js-components-grid-col.md +++ b/en/application-dev/reference/arkui-js/js-components-grid-col.md @@ -1,257 +1,70 @@ -# grid-col +# grid-col -The **** is the child component of the **** container. +> **NOTE** +> +> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** is the child component of the **\** container. -None. +## Required Permissions -## Child Components +None + + +## Child Components Supported -## Attributes -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +## Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

xs

-

number|object

-

-

-

No

-

Number of columns occupied by this item and offset columns when sizetype is xs. If you set the value of the number type, you only set the number of occupied columns. You can set a value of the object type for both the number of occupied columns and offset columns, for example, {"span": 1, "offset": 0}.

-

sm

-

number|object

-

-

-

No

-

Number of columns occupied by this item and offset columns when sizetype is sm. If you set the value of the number type, you only set the number of occupied columns. You can set a value of the object type for both the number of occupied columns and offset columns, for example, {"span": 1, "offset": 0}.

-

md

-

number|object

-

-

-

No

-

Number of columns occupied by this item and offset columns when sizetype is md. If you set the value of the number type, you only set the number of occupied columns. You can set a value of the object type for both the number of occupied columns and offset columns, for example, {"span": 1, "offset": 0}.

-

lg

-

number|object

-

-

-

No

-

Number of columns occupied by this item and offset columns when sizetype is lg. If you set the value of the number type, you only set the number of occupied columns. You can set a value of the object type for both the number of occupied columns and offset columns, for example, {"span": 1, "offset": 0}.

-

span

-

number

-

1

-

No

-

Default number of columns occupied by this item when no breakpoint is set.

-

offset

-

number

-

0

-

No

-

Default number of offset columns in the container layout direction when "offset" is not set for a specific sizetype.

-
+In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -## Styles +| Name | Type | Default Value | Mandatory | Description | +| ------ | -------------- | ---- | ---- | ---------------------------------------- | +| xs | number\|object | - | No | Number of columns occupied by this item and its offset when **sizetype** is **xs**. If you set the value of the number type, you only set the number of columns. You can set a value of the object type for both the number of occupied columns and the offset, for example, **{"span": 1, "offset": 0}**. | +| sm | number\|object | - | No | Number of columns occupied by this item and its offset when **sizetype** is **sm**. If you set the value of the number type, you only set the number of columns. You can set a value of the object type for both the number of occupied columns and the offset, for example, **{"span": 1, "offset": 0}**. | +| md | number\|object | - | No | Number of columns occupied by this item and its offset when **sizetype** is **md**. If you set the value of the number type, you only set the number of columns. You can set a value of the object type for both the number of occupied columns and the offset, for example, **{"span": 1, "offset": 0}**. | +| lg | number\|object | - | No | Number of columns occupied by this item and its offset when **sizetype** is **lg**. If you set the value of the number type, you only set the number of columns. You can set a value of the object type for both the number of occupied columns and the offset, for example, **{"span": 1, "offset": 0}**. | +| span | number | 1 | No | Default number of columns occupied by the item when no breakpoint is set. | +| offset | number | 0 | No | Default number of offset columns in the container layout direction when **"offset"** is not set for a specific **sizetype**. | -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

flex-direction

-

string

-

row

-

No

-

Main axis direction of the container. Available values are as follows:

-
  • column: Items are placed vertically from top to bottom.
  • row: Items are placed horizontally from left to right.
-

flex-wrap

-

string

-

nowrap

-

No

-

Whether items in the container are displayed in a single axis or multiple axes. Currently, dynamic modification is not supported. Available values are as follows:

-
  • nowrap: Items are displayed on a single axis.
  • wrap: Items are displayed on multiple axes.
-

justify-content

-

string

-

flex-start

-

No

-

How items are aligned along the main axis of the current row in the container. Available values are as follows:

-
  • flex-start: Items are packed towards the start row.
  • flex-end: Items are packed towards the end row.
  • center: Items are centered along the row.
  • space-between: Items are positioned with space between the rows.
  • space-around: Items are positioned with space before, between, and after the rows.
-

align-items

-

string

-

stretch

-

No

-

How items are aligned along the cross axis of the current row in the container. Available values are as follows:

-
  • stretch: Items are stretched to the same height or width as the container in the cross axis direction.
  • flex-start: Items are aligned to the start of the cross axis.
  • flex-end: Items are aligned to the end of the cross axis.
  • center: Items are aligned in the middle of the cross axis.
-

align-content

-

string

-

flex-start

-

No

-

Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:

-
  • flex-start: All rows are packed towards the start of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.
  • flex-end: All rows are packed towards the end of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.
  • center: All rows are packed towards the center of the container. Rows are close to each other and aligned with the center of the container. The spacing between the start of the container's cross axis and the first row is equal to the spacing between the end of the container's cross axis and the last row.
  • space-between: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.
  • space-around: All rows are evenly distributed in the container, and the spacing between two adjacent lines is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.
-

display

-

string

-

flex

-

No

-

Type of the view box of the element. Currently, dynamic modification is not supported. Available values are as follows:

-
  • flex: flexible layout.
  • grid: grid layout.
  • none: disabled.
-

grid-template-[columns|rows]

-

string

-

1 row, 1 column

-

No

-

Number of rows and columns in the current grid layout. If this attribute is not set, one row and one column are displayed by default. This attribute is valid only when display is set to grid.

-

For example, set grid-template-columns to:

-

(1) 50px 100px 60px: There are three columns. The first column is 50 px, the second column is 100 px, and the third column is 60 px.

-

(2) 1fr 1fr 2fr: There are three columns, and the width allowed by the parent component is divided into four equal shares. The first column occupies one share, the second column occupies one share, and the third column occupies two shares.

-

(3) 30% 20% 50%: There are three columns. The first column occupies 30% of the total width allowed by the parent component, the second column occupies 20%, and the third column occupies 50%.

-

(4) repeat (2,100px): There are two columns. The first column is 100 px, and the second column is 100 px.

-

(5) auto 1fr 1fr: There are three columns. The first column is adaptive to the width required by its child components. The remaining space is divided into two equal shares, one share occupied by each of the two columns.

-

grid-[columns|rows]-gap

-

<length>

-

0

-

No

-

Size of the gap between two consecutive rows or columns in a grid layout. You can also use grid-gap to set the same size of the gap between rows and columns. This attribute is valid only when display is set to grid.

-

grid-row-[start|end]

-

number

-

-

-

No

-

Start and end row numbers of the current item in the grid layout. This attribute is valid only when display of the parent component is grid. (The display attribute of the parent component can be set to grid only for the <div> container.)

-

grid-column-[start|end]

-

number

-

-

-

No

-

Start and end column numbers of the current item in the grid layout. This attribute is valid only when display of the parent component is grid. (The display attribute of the parent component can be set to grid only for the <div> container.)

-
+## Styles ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->Width-related styles are not supported. +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -## Events +| Name | Type | Default Value | Mandatory | Description | +| ----------------------------- | -------------- | ---------- | ---- | ---------------------------------------- | +| flex-direction | string | row | No | Main axis direction of the flex container, which defines how items are placed in the container. Available values are as follows:
- **column**: Items are placed vertically from top to bottom.
- **row**: Items are placed horizontally from left to right.| +| flex-wrap | string | nowrap | No | Whether items in the flex container are displayed in a single line or multiple lines. The value cannot be dynamically updated. Available values are as follows:
- **nowrap**: Items are displayed on a single axis.
- **wrap**: Items are displayed on multiple axes.| +| justify-content | string | flex-start | No | How items are aligned along the main axis of the flex container. Available values are as follows:
- **flex-start**: Items are packed towards the start row.
- **flex-end**: Items are packed towards the end row.
- **center**: Items are centered along the row.
- **space-between**: Items are positioned with space between the rows.
- **space-around**: Items are positioned with space before, between, and after the rows.| +| align-items | string | stretch | No | How items are aligned along the cross axis in a flex container. Available values are as follows:
- **stretch**: Items are stretched to the same height or width as the container in the cross axis direction.
- **flex-start**: Items are aligned to the start of the cross axis.
- **flex-end**: Items are aligned to the end of the cross axis.
- **center**: Items are aligned in the center of the cross axis.| +| align-content | string | flex-start | No | Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:
- **flex-start**: All rows are packed towards the start of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.
- **flex-end**: All rows are packed towards the end of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.
- **center**: All rows are packed towards the center of the container. Rows are close to each other and aligned with the center of the container. The spacing between the start edge of the container's cross axis and the first row is equal to the spacing between the end edge of the container's cross axis and the last row.
- **space-between**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.
- **space-around**: All rows are evenly distributed in the container, and the spacing between two adjacent lines is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.| +| display | string | flex | No | Type of the view box of the item. The value cannot be dynamically updated. Available values are as follows:
- **flex**: flexible layout.
- **grid**: grid layout.
- **none**: The box is disabled.| +| grid-template-[columns\|rows] | string | 1 row, 1 column | No | Number of rows and columns in the current grid layout. If this attribute is not set, one row and one column are displayed by default. This attribute is valid only when **display** is set to **grid**.
Below are some example values of **grid-template-columns**:
- **50px 100px 60px**: There are three columns. The first column is 50 px, the second column is 100 px, and the third column is 60 px.
- **1fr 1fr 2fr**: There are three columns, and the width allowed by the parent component is divided into four equal shares. The first column occupies one share, the second column occupies one share, and the third column occupies two shares.
- **30% 20% 50%**: There are three columns. The first column occupies 30% of the total width allowed by the parent component, the second column occupies 20%, and the third column occupies 50%.
- **repeat (2,100px)**: There are two columns. The first column is 100 px, and the second column is 100 px.
- **auto 1fr 1fr**: There are three columns. The first column is adaptive to the width required by its child components. The remaining space is divided into two equal shares, one share occupied by each of the rest two columns.| +| grid-[columns\|rows]-gap | <length> | 0 | No | Size of the gap between two consecutive rows or columns in a grid layout. You can also use **grid-gap** to set the same size of the gap between rows and columns. This attribute is valid only when **display** is set to **grid**.| +| grid-row-[start\|end] | number | - | No | Start and end row numbers of the current item in the grid layout. This attribute is valid only when the item's parent component is a **\
** container whose **display** style is set to **grid**.| +| grid-column-[start\|end] | number | - | No | Start and end column numbers of the current item in the grid layout. This attribute is valid only when the item's parent component is a **\
** container whose **display** style is set to **grid**.| -Events in [Universal Events](js-components-common-events.md) are supported. +> **NOTE** +> +> Width-related styles are not supported. -## Methods -Methods in [Universal Methods](js-components-common-methods.md) are supported. +## Events -## Example +The [universal events](../arkui-js/js-components-common-events.md) are supported. -``` + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +```html
@@ -271,7 +84,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported.
``` -``` +```css /* index.css */ .container { flex-direction: column; @@ -279,7 +92,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -``` +```js // index.js import prompt from '@system.prompt'; export default { @@ -302,5 +115,4 @@ export default { } ``` -![](figures/grid.gif) - +![grid](figures/grid.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-grid-container.md b/en/application-dev/reference/arkui-js/js-components-grid-container.md index 9bec017c1a2eb9018b69108c352b300a43055671..ba23181e0aaedc9ebaa1a68b51f58e8ddffbe2ad 100644 --- a/en/application-dev/reference/arkui-js/js-components-grid-container.md +++ b/en/application-dev/reference/arkui-js/js-components-grid-container.md @@ -1,279 +1,77 @@ -# grid-container +# grid-container -The **** component is the root container of the grid layout. Within the root container, you can use **** and **** for the grid layout. +> **NOTE** +> +> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. + +The **\** component is the root container of the grid layout. Within the root container, you can use **\** and **\** for the grid layout. -## Required Permissions +## Required Permissions None -## Child Component -Only the **** component is supported. +## Child Components + +Only the **\** component is supported. + -## Attributes +## Attributes -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

columns

-

string | number

-

auto

-

No

-

Total number of columns in the grid. If a value of the string type is set, it can only be auto. In this case, the total number of columns is determined based on the current sizetype, which can be one of the following values:

-
  • xs: 2 columns
  • sm: 4 columns
  • md: 8 columns
  • lg: 12 columns
-

sizetype

-

string

-

auto

-

No

-

Size-responsive type of the grid. Available values are xs, sm, md, and lg. If the default value auto is used, the framework automatically selects one of the four types based on the current container size.

-

gutter

-

<length>

-

24px

-

No

-

Gutter width

-

gridtemplate6+

-

string

-

default

-

No

-

Layout template of the grid, which defines the columns, gutters, and margins for different size-responsive types. This attribute is available when columns and sizetype are set to auto. For details about the values, see gridtemplate options.

-
+| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| columns | string \| number | auto | No| Total number of columns in the grid. If a value of the string type is set, it can only be **auto**. In this case, the total number of columns is determined based on the current **sizetype**, which can be one of the following values:
- **xs**: 2 columns
- **sm**: 4 columns
- **md**: 8 columns
- **lg**: 12 columns| +| sizetype | string | auto | No| Size-responsive type of the grid. Available values are **xs**, **sm**, **md**, and **lg**. If the default value **auto** is used, the framework automatically selects one of the four types based on the current container size.| +| gutter | <length> | 24px | No| Gutter width.| +| gridtemplate6+ | string | default | No| Layout template of the grid, which defines the columns, gutters, and margins for different size-responsive types. This attribute is available when **columns** and **sizetype** are set to **auto**. For details about the values, see **gridtemplate**.| -**Table 1** gridtemplate options6+ +**Table 1** gridtemplate6+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  

Template Value

-

Size-responsive Type

-

Columns

-

Margins(px)

-

Gutters(px)

-

Default grid

-

default

-

xs

-

2

-

12

-

12

-

sm

-

4

-

24

-

24

-

md

-

8

-

32

-

24

-

lg

-

12

-

48

-

24

-

Grid layout

-

grid

-

sm (0 < device horizontal resolution < 600px)

-

4

-

24

-

12

-

md

-

8

-

32

-

12

-

lg

-

12

-

48

-

12

-
+| | Template Value| Size-responsive Type| Columns | Margins (px) | Gutters (px) | +| -------- | -------- | -------- | -------- | -------- | -------- | +| Default grid| default | xs | 2 | 12 | 12 | +| | | sm | 4 | 24 | 24 | +| | | md | 8 | 32 | 24 | +| | | lg | 12 |48|24| +| Grid layout| grid | sm (0 < Device horizontal resolution < 600px)| 4 | 24 | 12 | +| | | md | 8 |32|12| +| | | lg | 12 |48|12| ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +> **NOTE** > ->- The px unit is applicable when **autoDesignWidth** is set to **true** in the "js" tag. 6+ +> The px unit is applicable when **autoDesignWidth** is set to **true** in the "js" tag.6+ + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -## Styles +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| justify-content | string | flex-start | No| How items are aligned along the main axis of the flex container. Available values are as follows:
- **flex-start**: Items are packed towards the start row.
- **flex-end**: Items are packed towards the end row.
- **center**: Items are centered along the row.
- **space-between**: Items are positioned with space between the rows.
- **space-around**: Items are positioned with space before, between, and after the rows.| +| align-items | string | stretch | No| How items are aligned along the cross axis in a flex container. Available values are as follows:
- **stretch**: Items are stretched to the same height or width as the container in the cross axis direction.
- **flex-start**: Items are aligned to the start of the cross axis.
- **flex-end**: Items are aligned to the end of the cross axis.
- **center**: Items are aligned in the center of the cross axis.| +| align-content | string | flex-start | No| Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:
- **flex-start**: All rows are packed towards the start of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.
- **flex-end**: All rows are packed towards the end of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.
- **center**: All rows are packed towards the center of the container. Rows are close to each other and aligned with the center of the container. The spacing between the start edge of the container's cross axis and the first row is equal to the spacing between the end edge of the container's cross axis and the last row.
- **space-between**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.
- **space-around**: All rows are evenly distributed in the container, and the spacing between two adjacent lines is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.| -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

justify-content

-

string

-

flex-start

-

No

-

How items are aligned along the main axis of the current row in the container. Available values are as follows:

-
  • flex-start: Items are packed towards the start row.
  • flex-end: Items are packed towards the end row.
  • center: Items are centered along the row.
  • space-between: Items are positioned with space between the rows.
  • space-around: Items are positioned with space before, between, and after the rows.
-

align-items

-

string

-

stretch

-

No

-

How items are aligned along the cross axis of the current row in the container. Available values are as follows:

-
  • stretch: Items are stretched to the same height or width as the container in the cross axis direction.
  • flex-start: Items are aligned to the start of the cross axis.
  • flex-end: Items are aligned to the end of the cross axis.
  • center: Items are aligned in the middle of the cross axis.
-

align-content

-

string

-

flex-start

-

No

-

Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:

-
  • flex-start: All rows are packed towards the start of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.
  • flex-end: All rows are packed towards the end of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.
  • center: All rows are packed towards the center of the container. Rows are close to each other and aligned with the center of the container. The spacing between the start of the container's cross axis and the first row is equal to the spacing between the end of the container's cross axis and the last row.
  • space-between: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.
  • space-around: All rows are evenly distributed in the container, and the spacing between two adjacent rows is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.
-
+## Events -## Events +The [universal events](../arkui-js/js-components-common-events.md) are supported. -Events in [Universal Events](js-components-common-events.md) are supported. -## Method +## Methods -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

getColumns

-

-

-

Returns the number of columns in the grid.

-

getColumnWidth

-

-

-

Returns the column width of the grid.

-

getGutterWidth

-

-

-

Returns the gutter width between columns of the grid.

-

getSizeType

-

-

-

Returns the size-responsive type of the grid container, which can be xs, sm, md, or lg.

-
+| Name| Parameter| Description| +| -------- | -------- | -------- | +| getColumns | - | Returns the number of columns in the grid.| +| getColumnWidth | - | Returns the column width of the grid.| +| getGutterWidth | - | Returns the gutter width between columns of the grid.| +| getSizeType | - | Returns the size-responsive type of the grid container (xs\|sm\|md\|lg).| -## Example Code -For details, see [grid-col](js-components-grid-col.md). +## Example +For details, see [Example in grid-col](../arkui-js/js-components-grid-col.md#example). diff --git a/en/application-dev/reference/arkui-js/js-components-grid-row.md b/en/application-dev/reference/arkui-js/js-components-grid-row.md index ffb31abdb1fa5fdfad533a54cd47e8a5bc75dae5..38856e883096a8d03ee0d53cc2f1b7afd628df08 100644 --- a/en/application-dev/reference/arkui-js/js-components-grid-row.md +++ b/en/application-dev/reference/arkui-js/js-components-grid-row.md @@ -1,99 +1,52 @@ -# grid-row +# grid-row -The **** component is a container used as a child component of ****. Each **** component is arranged horizontally with **flex**-related styles. By default, items in the **** component are packed towards the start row and aligned to the start of the cross axis. You can set the items to be displayed in multiple axes. +> **NOTE** +> +> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component is a container used as a child component of **\**. Each **\** component is arranged horizontally with **flex**-related styles. By default, items in the **\** component are packed towards the start row and aligned to the start of the cross axis. You can set the items to be displayed in multiple axes. + +## Required Permissions None -## Child Components - -Only the **** component is supported. - -## Attributes - -Attributes in [Universal Attributes](js-components-common-attributes.md) are supported. - -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

flex-wrap

-

string

-

nowrap

-

No

-

Whether items in the container are displayed in a single axis or multiple axes. Currently, dynamic modification is not supported. Available values are as follows:

-
  • nowrap: Items are displayed on a single axis.
  • wrap: Items are displayed on multiple axes.
-

justify-content

-

string

-

flex-start

-

No

-

How items are aligned along the main axis of the current row in the container. Available values are as follows:

-
  • flex-start: Items are packed towards the start row.
  • flex-end: Items are packed towards the end row.
  • center: Items are centered along the row.
  • space-between: Items are positioned with space between the rows.
  • space-around: Items are positioned with space before, between, and after the rows.
-

align-items

-

string

-

flex-start

-

No

-

How items are aligned along the cross axis of the current row in the container. Available values are as follows:

-
  • stretch: Items are stretched to the same height or width as the container in the cross axis direction.
  • flex-start: Items are aligned to the start of the cross axis.
  • flex-end: Items are aligned to the end of the cross axis.
  • center: Items are aligned in the middle of the cross axis.
-

align-content

-

string

-

flex-start

-

No

-

Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:

-
  • flex-start: All rows are packed towards the start of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.
  • flex-end: All rows are packed towards the end of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.
  • center: All rows are packed towards the center of the container. Rows are close to each other and aligned with the center of the container. The spacing between the start of the container's cross axis and the first row is equal to the spacing between the end of the container's cross axis and the last row.
  • space-between: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.
  • space-around: All rows are evenly distributed in the container, and the spacing between two adjacent rows is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.
-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->Width-related styles are not supported. - -## Events - -Events in [Universal Events](js-components-common-events.md) are supported. - -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example Code - -For details, see [grid-col](js-components-grid-col.md). +## Child Components + +Only the **\** component is supported. + + +## Attributes + +The [universal attributes](../arkui-js/js-components-common-attributes.md) are supported. + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| flex-wrap | string | nowrap | No| Whether items in the flex container are displayed in a single line or multiple lines. The value cannot be dynamically updated. Available values are as follows:
- **nowrap**: Items are displayed on a single axis.
- **wrap**: Items are displayed on multiple axes.| +| justify-content | string | flex-start | No| How items are aligned along the main axis of the flex container. Available values are as follows:
- **flex-start**: Items are packed towards the start row.
- **flex-end**: Items are packed towards the end row.
- **center**: Items are centered along the row.
- **space-between**: Items are positioned with space between the rows.
- **space-around**: Items are positioned with space before, between, and after the rows.| +| align-items | string | flex-start | No| How items are aligned along the cross axis in a flex container. Available values are as follows:
- **stretch**: Items are stretched to the same height or width as the container in the cross axis direction.
- **flex-start**: Items are aligned to the start of the cross axis.
- **flex-end**: Items are aligned to the end of the cross axis.
- **center**: Items are aligned in the center of the cross axis.| +| align-content | string | flex-start | No| Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:
- **flex-start**: All rows are packed towards the start of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.
- **flex-end**: All rows are packed towards the end of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.
- **center**: All rows are packed towards the center of the container. Rows are close to each other and aligned with the center of the container. The spacing between the start edge of the container's cross axis and the first row is equal to the spacing between the end edge of the container's cross axis and the last row.
- **space-between**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.
- **space-around**: All rows are evenly distributed in the container, and the spacing between two adjacent lines is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.| + +> **NOTE** +> +> Width-related styles are not supported. + + +## Events + +The [universal events](../arkui-js/js-components-common-events.md) are supported. + + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +For details, see [Example in grid-col](../arkui-js/js-components-grid-col.md#example). diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animate.md b/en/application-dev/reference/arkui-js/js-components-svg-animate.md index 751dbe4adb724775bc0cd287b47f29c25cbd2339..5bac399f7fc3fda58a705e692c5c99380c45d937 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animate.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animate.md @@ -1,201 +1,45 @@ -# animate +# animate -The **** component is used to apply animation to an **** component. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component is used to apply animation to an **\** component. + +## Required Permissions None -## Child Components + +## Child Components Not supported -## Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

id

-

string

-

-

-

No

-

Unique ID of the component.

-

attributeName

-

string

-

-

-

No

-

Name of the component to which the animation is applied.

-

begin

-

<time>

-

0

-

No

-

Delay time of the animation.

-

The value can be ms (ms), s (second), or m (minute). The default value is s (second). Other formats are not supported.

-

dur

-

<time>

-

0

-

No

-

Animation duration. If dur is not set, the value of end-begin is used as the duration. If the value is less than or equal to 0, the animation is not triggered.

-

The value can be ms (ms), s (second), or m (minute). The default value is s (second). Other formats are not supported.

-

end

-

<time>

-

0

-

No

-

Duration after which the animation ends. The value can be ms (ms), s (second), or m (minute). The default value is s (second). Other formats are not supported.

-

repeatCount

-

<number | indefinite>

-

1

-

No

-

Number of times the animation is played. The default value is indefinite. You can set the value to 1 to play the animation only once.

-

fill

-

<freeze | remove>

-

remove

-

No

-

State when the animation ends.

-

calcMode

-

<discrete | linear | paced | spline>

-

linear

-

No

-

Interpolation mode of the animation.

-

discrete: The value of from directly jumps to the value of to.

-

linear: linear.

-

paced: linear. After this value is set, the values of keyTimes and keyPoints are invalid.

-

spline: user-defined Bessel curve. The spline point is defined in the keyTimes attribute, and the control point of each interval is defined by keySplines.

-

keyTimes

-

string

-

-

-

No

-

Start time of the key frame animation. The value ranges from 0 to 1, separated by semicolons (;), for example, 0;0.3;0.8;1. keyTimes, keySplines, and values are combined to set the key frame animation. The number of keyTimes is the same as that of values. The number of keySplines is the number of keyTimes minus 1.

-

keySplines

-

string

-

-

-

No

-

A set of Bessel control points associated with keyTimes. You can define the Bessel curves for each key frame. The curves are separated by semicolons (;). The format of the two controls in the curve is x1 y1 x2 y2. For example, 0.5 0 0.5 1; 0.5 0 0.5 1;0.5 0 0.5 1.

-

by

-

number

-

-

-

No

-

Relative offset value to add to a specified attribute in the animation. The default value of from is the original attribute value.

-

from

-

string

-

-

-

No

-

Start value of the attribute to which the animation is applied.

-

If the values attribute has been set, the from attribute is invalid.

-

to

-

string

-

-

-

No

-

End value of the attribute to which the animation is applied.

-

If the values attribute has been set, the to attribute is invalid.

-

values

-

string

-

-

-

No

-

Change value of a group of animations. The format is value1;value2;value3.

-
+## Attributes -## Example +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| id | string | - | No| Unique ID of the component.| +| attributeName | string | - | No| Name of the component to which the animation is applied.| +| begin | <time> | 0 | No| Delay time of the animation.
The value can be ms (ms), s (second), or m (minute). The default value is s (second). Other formats are not supported.| +| dur | <time> | 0 | No| Animation duration. If **dur** is not set, the value of **end**-**begin** is used as the duration. If the value is less than or equal to 0, the animation is not triggered.
The value can be ms (ms), s (second), or m (minute). The default value is s (second). Other formats are not supported.| +| end | <time> | 0 | No| Duration after which the animation ends. The value can be ms (ms), s (second), or m (minute). The default value is s (second). Other formats are not supported.| +| repeatCount | <number \| indefinite> | 1 | No| Number of times the animation is played. The default value is indefinite. You can set the value to **1** to play the animation only once.| +| fill | <freeze \| remove> | remove | No| State when the animation ends.| +| calcMode | <discrete \| linear \| paced \| spline> | linear | No| Interpolation mode of the animation.
**discrete**: The value of **from** directly jumps to the value of **to**.
**linear**: linear.
**paced**: linear. After this value is set, the values of **keyTimes** and **keyPoints** are invalid.
**spline**: user-defined Bessel curve. The spline point is defined in the **keyTimes** attribute, and the control point of each interval is defined by **keySplines**.| +| keyTimes | string | - | No| Start time of the key frame animation. The value ranges from 0 to 1, separated by semicolons (;), for example, **0;0.3;0.8;1**. **keyTimes**, **keySplines**, and **values** are combined to set the key frame animation. The number of **keyTimes** is the same as that of **values**. The number of **keySplines** is the number of **keyTimes** minus 1.| +| keySplines | string | - | No| A set of Bessel control points associated with **keyTimes**. You can define the Bessel curves for each key frame. The curves are separated by semicolons (;). The format of the two controls in the curve is x1 y1 x2 y2. For example, **0.5 0 0.5 1; 0.5 0 0.5 1;0.5 0 0.5 1**.| +| by | number | - | No| Relative offset value to add to a specified attribute in the animation. The default value of **from** is the original attribute value.| +| from | string | - | No| Start value of the attribute to which the animation is applied.
If the **values** attribute has been set, the **from** attribute is invalid.| +| to | string | - | No| End value of the attribute to which the animation is applied.
If the **values** attribute has been set, the **to** attribute is invalid.| +| values | string | - | No| Change value of a group of animations. The format is value1;value2;value3.| -``` + +## Example + +```html
@@ -207,9 +51,11 @@ Not supported
``` -![](figures/animate-1.gif) -``` +![zh-cn_image_0000001173324703](figures/zh-cn_image_0000001173324703.gif) + + +```html
@@ -221,9 +67,11 @@ Not supported
``` -![](figures/1-10.gif) -``` +![zh-cn_image_0000001167662852](figures/zh-cn_image_0000001167662852.gif) + + +```html
@@ -234,9 +82,11 @@ Not supported
``` -![](figures/animate-3.gif) -``` +![zh-cn_image_0000001127284938](figures/zh-cn_image_0000001127284938.gif) + + +```html
@@ -266,5 +116,5 @@ Not supported
``` -![](figures/animate-4.gif) +![animate-4](figures/animate-4.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animatemotion.md b/en/application-dev/reference/arkui-js/js-components-svg-animatemotion.md index ab8d768fbd7e9333c4876dea209c88da6de576e1..9cdfadcd42018cb2ee2ba98ca39f1613af97c197 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animatemotion.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animatemotion.md @@ -1,74 +1,36 @@ -# animateMotion +# animateMotion -The **** component is used to define the animation along a path. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component is used to define the animation along a path. -None +## Required Permissions -## Child Components +None. + + +## Child Components Not supported -## Attributes - -The **animate** attributes \(**values** does not take effect\) and the attributes in the following table are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

keyPoints

-

string

-

-

-

Yes

-

Point position of a group of key frames. The value of each frame is the distance proportion of the object along the path. The function is the same as that of values in the animate attribute.

-

path

-

string

-

-

-

Yes

-

Motion path. The syntax is the same as that of the d attribute of the <path> component.

-

rotate

-

[auto | auto-reverse | <number>]

-

auto

-

-

-

Rotation direction of an animation object.

-
- -## Example -``` +## Attributes + +The **animate** attributes (**values** does not take effect) and the attributes in the following table are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| keyPoints | string | - | Yes| Point position of a group of key frames. The value of each frame is the distance proportion of the object along the path. The function is the same as that of **values** in the **animate** attribute.| +| path | string | - | Yes| Motion path. The syntax is the same as that of the **d** attribute of the **\** component. | +| rotate | [auto \| auto-reverse \| <number>] | auto | No| Rotation direction of an animation object.| + + +## Example + +```html
@@ -90,5 +52,5 @@ The **animate** attributes \(**values** does not take effect\) and the attrib
``` -![](figures/2-11.gif) +![2-11](figures/2-11.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md b/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md index 4b4cf63bcb25cd7e8a7abc010ae91af3bb308ad6..3a38de3abca726638e2a039a2063309a572ea264 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md @@ -1,54 +1,37 @@ -# animateTransform +# animateTransform -The **** component is used to apply a transform animation and supports the following components: -, , , , , , , +> **NOTE** +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to apply a transform animation and supports the following components: -## Required Permissions + +<circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>, <text> + +## Required Permissions None -## Child Components + +## Child Components Not supported -## Attributes - -The **animate** attributes and the attributes in the following table are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

[translate | scale | rotate | skewX | skewY]

-

-

-

Yes

-

Transform animation type.

-
- -## Example -``` +## Attributes + +The **animate** attributes and the attributes in the following table are supported. + +| Name| Type| Default Value| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | +| type | [translate \| scale \| rotate \| skewX \| skewY] | - | Yes| Transform animation type.| + + +## Example + +```html
@@ -89,7 +72,7 @@ The **animate** attributes and the attributes in the following table are suppo
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -107,11 +90,14 @@ The **animate** attributes and the attributes in the following table are suppo } ``` -![](figures/animate-transform.gif) + +![animate-transform](figures/animate-transform.gif) + Animation overlay -``` + +```html
@@ -145,7 +131,8 @@ Animation overlay
``` -``` + +```css /* xxx.css */ .container { flex-direction: column; @@ -162,11 +149,14 @@ Animation overlay } ``` -![](figures/animate-transform2.gif) -Involved component example +![animate-transform2](figures/animate-transform2.gif) -``` + +Example of involved components + + +```html
@@ -212,7 +202,8 @@ Involved component example
``` -``` + +```css /* xxx.css */ .container { flex-direction: column; @@ -229,5 +220,5 @@ Involved component example } ``` -![](figures/animate-transform3.gif) +![animate-transform3](figures/animate-transform3.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-svg-textpath.md b/en/application-dev/reference/arkui-js/js-components-svg-textpath.md index 536971760c5a2e5e56d01fbab11535406f83f55a..146d99f2bb9e2ee0d9fcce211be83897bd4a08cf 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-textpath.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-textpath.md @@ -26,19 +26,19 @@ The **[\](js-components-svg-tspan.md)** child component is supported. The attributes in the following table are supported. -| Name | Type | Default Value| Description | +| Name | Type | Mandatory | Description | | -------------- | ---------------------------------- | ------ | ------------------------------------------------------------ | | id | string | - | Unique ID of the component. | -| path | string | 0 | Shape of the path.
The meanings of the letters are as follows:
- M = moveto
- L = lineto
- H = horizontal lineto
- V = vertical lineto
- C = curveto
- S = smooth curveto
- Q = quadratic Belzier curve
- T = smooth quadratic Belzier curveto
- A = elliptical Arc
- Z = closepath
Default value: **0**| -| startOffset | <length>\|<percentage> | 0 | Offset of the text start point relative to the path start point.
Default value: **0** | -| font-size | <length> | 30px | Font size.
Default value: **30px** | -| fill | <color> | black | Font fill color.
Default value: **black** | -| by | number | - | Attribute offset relative to the specified animation. By default, **from** is the original attribute value. | -| opacity | number | 1 | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.
Default value: **0**| -| fill-opacity | number | 1.0 | Font fill opacity.
Default value: **1.0** | -| stroke | <color> | black | Stroke color.
Default value: **black** | -| stroke-width | number | 1px | Stroke width.
Default value: **1px** | -| stroke-opacity | number | 1.0 | Stroke opacity.
Default value: **1.0** | +| path | string | No | Shape of the path.
The meanings of the letters are as follows:
- M = moveto
- L = lineto
- H = horizontal lineto
- V = vertical lineto
- C = curveto
- S = smooth curveto
- Q = quadratic Belzier curve
- T = smooth quadratic Belzier curveto
- A = elliptical Arc
- Z = closepath
Default value: **0**| +| startOffset | <length>\|<percentage> | Yes | Offset of the text start point relative to the path start point.
Default value: **0** | +| font-size | <length> | No | Font size.
Default value: **30px** | +| fill | <color> | No | Font fill color.
Default value: **black** | +| by | number | No | Attribute offset relative to the specified animation. By default, **from** is the original attribute value. | +| opacity | number | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.
Default value: **0**| +| fill-opacity | number | No | Font fill opacity.
Default value: **1.0** | +| stroke | <color> | No | Stroke color.
Default value: **black** | +| stroke-width | number | No | Stroke width.
Default value: **1px** | +| stroke-opacity | number | No | Stroke opacity.
Default value: **1.0** | ## Example diff --git a/en/application-dev/reference/arkui-js/js-components-svg.md b/en/application-dev/reference/arkui-js/js-components-svg.md index 1ac5d3f287246d41e586a71069c892774e3533a3..5211d35eb04004f778dfeb151b70f1fe17fefe04 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg.md +++ b/en/application-dev/reference/arkui-js/js-components-svg.md @@ -6,7 +6,7 @@ The **\** component is a basic container. It can be used as the root node o > **NOTE** > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > -> - The width and height must be defined for the **** parent component or **** component. Otherwise, the component is not drawn. +> - The width and height must be defined for the **\** parent component or **\** component. Otherwise, the component is not drawn. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md index 53cce764385f29e9ef9a2b65043dad9f2be90d7f..92b1f801728b7bca689f7810b34741b743918124 100644 --- a/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md @@ -1,337 +1,218 @@ -# OffscreenCanvasRenderingContext2D - - ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->**OffscreenCanvasRenderingContext2D** is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - -Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and texts on an **OffscreenCanvas**. - -## Attributes - -In addition to the attributes that are supported by **CanvasRenderingContext2D**, the following attributes are supported. - - - - - - - - - - - - -

Name

-

Type

-

Description

-

filter

-

string

-

Image filter.

-

Available options are as follows:

-
  • blur: applies the Gaussian blur for the image.
  • brightness: applies a linear multiplication to the image to make it look brighter or darker.
  • contrast: adjusts the image contrast.
  • drop-shadow: sets a shadow effect for the image.
  • grayscale: converts the image to a grayscale image.
  • hue-rotate: applies hue rotation to the image.
  • invert: inverts the input image.
  • opacity: opacity of the converted image.
  • saturate: saturation of the converted image.
  • sepia: converts the image to dark brown.
-
- -- Example - - ``` - -
- -
- ``` - - ``` - //xxx.js - export default { - onShow(){ - var ctx = this.$refs.canvasId.getContext('2d'); - var offscreen = new OffscreenCanvas(360, 500); - var offCanvas2 = offscreen.getContext("2d"); - var img = new Image(); - img.src = 'common/images/flower.jpg'; - offCanvas2.drawImage(img, 0, 0, 100, 100); - offCanvas2.filter = 'blur(5px)'; - offCanvas2.drawImage(img, 100, 0, 100, 100); - - offCanvas2.filter = 'grayscale(50%)'; - offCanvas2.drawImage(img, 200, 0, 100, 100); - - offCanvas2.filter = 'hue-rotate(90deg)'; - offCanvas2.drawImage(img, 0, 100, 100, 100); - - offCanvas2.filter = 'invert(100%)'; - offCanvas2.drawImage(img, 100, 100, 100, 100); - - offCanvas2.filter = 'drop-shadow(8px 8px 10px green)'; - offCanvas2.drawImage(img, 200, 100, 100, 100); - - offCanvas2.filter = 'brightness(0.4)'; - offCanvas2.drawImage(img, 0, 200, 100, 100); - - offCanvas2.filter = 'opacity(25%)'; - offCanvas2.drawImage(img, 100, 200, 100, 100); - - offCanvas2.filter = 'saturate(30%)'; - offCanvas2.drawImage(img, 200, 200, 100, 100); - - offCanvas2.filter = 'sepia(60%)'; - offCanvas2.drawImage(img, 0, 300, 100, 100); - - offCanvas2.filter = 'contrast(200%)'; - offCanvas2.drawImage(img, 100, 300, 100, 100); - var bitmap = offscreen.transferToImageBitmap(); - ctx.transferFromImageBitmap(bitmap); - } - } - ``` - - - -## Methods - -In addition to the attributes that are supported by **CanvasRenderingContext2D**, the following attributes are supported. - -### isPointInPath - -isPointInPath\(path?: Path2D, x: number, y: number\): boolean +# OffscreenCanvasRenderingContext2D + +> **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. + + +Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and texts on an **OffscreenCanvas**. + + +## Attributes + +In addition to the attributes that are supported by **CanvasRenderingContext2D**, the following attributes are supported. + +| Name | Type | Description | +| ------ | ------ | ---------------------------------------- | +| filter | string | Image filter.
Available options are as follows:
- **blur**: applies the Gaussian blur for the image.
- **brightness**: applies a linear multiplication to the image to make it look brighter or darker.
- **contrast**: adjusts the image contrast.
- **drop-shadow**: sets a shadow effect for the image.
- **grayscale**: converts the image to a grayscale image.
- **hue-rotate**: applies hue rotation to the image.
- **invert**: inverts the input image.
- **opacity**: sets the opacity of the image.
- **saturate**: sets the saturation of the image.
- **sepia**: converts the image to dark brown. | + +**Example** +```html + +
+ +
+``` + +```js +// xxx.js +export default { + onShow(){ + var ctx = this.$refs.canvasId.getContext('2d'); + var offscreen = new OffscreenCanvas(360, 500); + var offCanvas2 = offscreen.getContext("2d"); + var img = new Image(); + img.src = 'common/images/flower.jpg'; + offCanvas2.drawImage(img, 0, 0, 100, 100); + offCanvas2.filter = 'blur(5px)'; + offCanvas2.drawImage(img, 100, 0, 100, 100); + + offCanvas2.filter = 'grayscale(50%)'; + offCanvas2.drawImage(img, 200, 0, 100, 100); + + offCanvas2.filter = 'hue-rotate(90deg)'; + offCanvas2.drawImage(img, 0, 100, 100, 100); + + offCanvas2.filter = 'invert(100%)'; + offCanvas2.drawImage(img, 100, 100, 100, 100); + + offCanvas2.filter = 'drop-shadow(8px 8px 10px green)'; + offCanvas2.drawImage(img, 200, 100, 100, 100); + + offCanvas2.filter = 'brightness(0.4)'; + offCanvas2.drawImage(img, 0, 200, 100, 100); + + offCanvas2.filter = 'opacity(25%)'; + offCanvas2.drawImage(img, 100, 200, 100, 100); + + offCanvas2.filter = 'saturate(30%)'; + offCanvas2.drawImage(img, 200, 200, 100, 100); + + offCanvas2.filter = 'sepia(60%)'; + offCanvas2.drawImage(img, 0, 300, 100, 100); + + offCanvas2.filter = 'contrast(200%)'; + offCanvas2.drawImage(img, 100, 300, 100, 100); + var bitmap = offscreen.transferToImageBitmap(); + ctx.transferFromImageBitmap(bitmap); + } +} +``` + +## Methods + +In addition to the methods that are supported by **CanvasRenderingContext2D**, the following methods are supported. + + +### isPointInPath + +isPointInPath(path?: Path2D, x: number, y: number): boolean Checks whether a specified point is in the path area. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

path

-

Path2D

-

No

-

Path used for checking. If this parameter is not set, the current path is used.

-

x

-

number

-

Yes

-

X-coordinate of the point used for checking.

-

y

-

number

-

Yes

-

Y-coordinate of the point used for checking.

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

Type

-

Description

-

boolean

-

Whether a specified point is in the path area.

-
- -- Example - - ``` - -
- In path:{{textValue}} - -
- ``` - - ``` - // xxx.js - export default { - data: { - textValue: 0 - }, - onShow(){ - var canvas = this.$refs.canvas.getContext('2d'); - var offscreen = new OffscreenCanvas(500,500); - var offscreenCanvasCtx = offscreen.getContext("2d"); - - offscreenCanvasCtx.rect(10, 10, 100, 100); - offscreenCanvasCtx.fill(); - this.textValue = offscreenCanvasCtx.isPointInPath(30, 70); - - var bitmap = offscreen.transferToImageBitmap(); - canvas.transferFromImageBitmap(bitmap); - } - } - ``` - - ![](figures/en-us_image_0000001224354967.png) - - -### isPointInStroke - -isPointInStroke\(path?: Path2D, x: number, y: number\): boolean +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------------- | +| path | Path2D | No | Path used for checking. If this parameter is not set, the current path is used.| +| x | number | Yes | X-coordinate of the point used for checking. | +| y | number | Yes | Y-coordinate of the point used for checking. | + +**Return value** +| Type | Description | +| ------- | ------------- | +| boolean | Whether a specified point is in the path area.| + +**Example** +```html + +
+ In path:{{textValue}} + +
+``` + +```js +// xxx.js +export default { + data: { + textValue: 0 + }, + onShow(){ + var canvas = this.$refs.canvas.getContext('2d'); + var offscreen = new OffscreenCanvas(500,500); + var offscreenCanvasCtx = offscreen.getContext("2d"); + + offscreenCanvasCtx.rect(10, 10, 100, 100); + offscreenCanvasCtx.fill(); + this.textValue = offscreenCanvasCtx.isPointInPath(30, 70); + + var bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); + } +} +``` + +![en-us_image_0000001224354967](figures/en-us_image_0000001224354967.png) + +### isPointInStroke + +isPointInStroke(path?: Path2D, x: number, y: number): boolean Checks whether a specified point is on the edge line of a path. -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

path

-

Path2D

-

No

-

Path used for checking. If this parameter is not set, the current path is used.

-

x

-

number

-

Yes

-

X-coordinate of the point used for checking.

-

y

-

number

-

Yes

-

Y-coordinate of the point used for checking.

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

Type

-

Description

-

boolean

-

Whether a specified point is in the path area.

-
- -- Example - - ``` - -
- In path:{{textValue}} - -
- ``` - - ``` - // xxx.js - export default { - data: { - textValue: 0 - }, - onShow(){ - var canvas = this.$refs.canvas.getContext('2d'); - var offscreen = new OffscreenCanvas(500,500); - var offscreenCanvasCtx = offscreen.getContext("2d"); - - offscreenCanvasCtx.rect(10, 10, 100, 100); - offscreenCanvasCtx.stroke(); - this.textValue = offscreenCanvasCtx.isPointInStroke(50, 10); - - var bitmap = offscreen.transferToImageBitmap(); - canvas.transferFromImageBitmap(bitmap); - } - } - ``` - - ![](figures/en-us_image_0000001178875308.png) - - -### resetTransform - -resetTransform\(\): void - -- Example - - ``` - -
- In path:{{textValue}} - -
- ``` - - ``` - //xxx.js - export default { - data:{ - textValue:0 - }, - onShow(){ - var canvas = this.$refs.canvas.getContext('2d'); - var offscreen = new OffscreenCanvas(500,500); - var offscreenCanvasCtx = offscreen.getContext("2d"); - - offscreenCanvasCtx.transform(1, 0, 1.7, 1, 0, 0); - offscreenCanvasCtx.fillStyle = 'gray'; - offscreenCanvasCtx.fillRect(40, 40, 50, 20); - offscreenCanvasCtx.fillRect(40, 90, 50, 20); - - // Non-skewed rectangles - offscreenCanvasCtx.resetTransform(); - offscreenCanvasCtx.fillStyle = 'red'; - offscreenCanvasCtx.fillRect(40, 40, 50, 20); - offscreenCanvasCtx.fillRect(40, 90, 50, 20); - - var bitmap = offscreen.transferToImageBitmap(); - canvas.transferFromImageBitmap(bitmap); - } - } - ``` - - ![](figures/en-us_image_0000001179035242.png) - +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------------- | +| path | Path2D | No | Path used for checking. If this parameter is not set, the current path is used.| +| x | number | Yes | X-coordinate of the point used for checking. | +| y | number | Yes | Y-coordinate of the point used for checking. | + +**Return value** +| Type | Description | +| ------- | ------------- | +| boolean | Whether a specified point is in the path area.| + +**Example** +```html + +
+ In path:{{textValue}} + +
+``` + +```js +// xxx.js +export default { + data: { + textValue: 0 + }, + onShow(){ + var canvas = this.$refs.canvas.getContext('2d'); + var offscreen = new OffscreenCanvas(500,500); + var offscreenCanvasCtx = offscreen.getContext("2d"); + + offscreenCanvasCtx.rect(10, 10, 100, 100); + offscreenCanvasCtx.stroke(); + this.textValue = offscreenCanvasCtx.isPointInStroke(50, 10); + + var bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); + } +} +``` + +![en-us_image_0000001178875308](figures/en-us_image_0000001178875308.png) + +### resetTransform + +resetTransform(): void + +**Example** +```html + +
+ In path:{{textValue}} + +
+``` + +```js +// xxx.js +export default { + data:{ + textValue:0 + }, + onShow(){ + var canvas = this.$refs.canvas.getContext('2d'); + var offscreen = new OffscreenCanvas(500,500); + var offscreenCanvasCtx = offscreen.getContext("2d"); + + offscreenCanvasCtx.transform(1, 0, 1.7, 1, 0, 0); + offscreenCanvasCtx.fillStyle = 'gray'; + offscreenCanvasCtx.fillRect(40, 40, 50, 20); + offscreenCanvasCtx.fillRect(40, 90, 50, 20); + + // Non-skewed rectangles + offscreenCanvasCtx.resetTransform(); + offscreenCanvasCtx.fillStyle = 'red'; + offscreenCanvasCtx.fillRect(40, 40, 50, 20); + offscreenCanvasCtx.fillRect(40, 90, 50, 20); + + var bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); + } +} +``` + +![en-us_image_0000001179035242](figures/en-us_image_0000001179035242.png) diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 9f7f8eee53a8010ef0a5ee0dfd860af3b503ec8d..0f5ff9e7a6546f55133b805e794aeb19a7fce1a8 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -1,4 +1,4 @@ -# TypeScript-based Declarative Development Paradigm +# ArkTS-based Declarative Development Paradigm - Universal Component Information - Universal Events @@ -133,12 +133,13 @@ - Canvas Components - [Canvas](ts-components-canvas-canvas.md) - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) - - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) - - [Lottie](ts-components-canvas-lottie.md) - - [Path2D](ts-components-canvas-path2d.md) - [CanvasGradient](ts-components-canvas-canvasgradient.md) - [ImageBitmap](ts-components-canvas-imagebitmap.md) - [ImageData](ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) + - [Path2D](ts-components-canvas-path2d.md) + - [Lottie](ts-components-canvas-lottie.md) + - Animation - [AnimatorProperty](ts-animatorproperty.md) - [Explicit Animation](ts-explicit-animation.md) @@ -147,8 +148,7 @@ - [Component Transition](ts-transition-animation-component.md) - [Transition of Shared Elements](ts-transition-animation-shared-elements.md) - [Motion Path Animation](ts-motion-path-animation.md) - - [Matrix Transformation](ts-matrix-transformation.md) - - [Interpolation Calculation](ts-interpolation-calculation.md) + - Global UI Methods - Pop-up Window - [Alert Dialog Box](ts-methods-alert-dialog-box.md) @@ -159,3 +159,4 @@ - [Text Picker Dialog Box](ts-methods-textpicker-dialog.md) - [Menu](ts-methods-menu.md) - [Built-in Enums](ts-appendix-enums.md) +- [Types](ts-types.md) diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422904.jpg b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422904.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bf5c3a49c58818ec9dec43db3c2d4c5e16949a94 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422904.jpg differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png new file mode 100644 index 0000000000000000000000000000000000000000..c564bb26b539f1e48acbdb7f2aeeca8df4e4e798 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png new file mode 100644 index 0000000000000000000000000000000000000000..6c136313fe0c8774d1209a398d16ecc4b58c2bcd Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png new file mode 100644 index 0000000000000000000000000000000000000000..3e7218eb57566d86457a9fbd4a8ed0f0dd490c3f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png new file mode 100644 index 0000000000000000000000000000000000000000..a07986a04b7477eec14c81d08e442d7b332dab83 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png new file mode 100644 index 0000000000000000000000000000000000000000..3d93b0a0a8f5d0b527d407e450a4a13a1de991ab Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png new file mode 100644 index 0000000000000000000000000000000000000000..5c0a336a56d0e5a186bd235cd25f9f5e5e7e644f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png new file mode 100644 index 0000000000000000000000000000000000000000..2b9bc96da366d53da784c92620a69f602f7bff14 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png new file mode 100644 index 0000000000000000000000000000000000000000..27556ea43f7c2ecc65b9425e243ea593f02b08ec Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png new file mode 100644 index 0000000000000000000000000000000000000000..2a5c5649cc0716abc024aa3656924a456216a4c2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png new file mode 100644 index 0000000000000000000000000000000000000000..00097d258d585ec8ad981703c5b265679e867133 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png new file mode 100644 index 0000000000000000000000000000000000000000..1b1cedac00a77279faa829636bc85028fb5ec711 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png new file mode 100644 index 0000000000000000000000000000000000000000..5855095851b92058f270d69a46546db43ec974b8 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.png new file mode 100644 index 0000000000000000000000000000000000000000..9eb00739d606ea0b53542eba7c43f6cbb82c73c5 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png new file mode 100644 index 0000000000000000000000000000000000000000..81710c1186a0c0448d70a443db66c09a4e46d395 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png new file mode 100644 index 0000000000000000000000000000000000000000..5c75654b85d596a346fa5d793ca84991fe859a86 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png new file mode 100644 index 0000000000000000000000000000000000000000..defc3c9eb037c06b894ee2e30563facb8c8375ab Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png new file mode 100644 index 0000000000000000000000000000000000000000..abc9a5667500a749dbceee88aef4caebf5d9df18 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png new file mode 100644 index 0000000000000000000000000000000000000000..241fe8546ea2acfdb7baf2c5e66a8af2f0d7b593 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png new file mode 100644 index 0000000000000000000000000000000000000000..19e99b9ef490fff79e64e33192c97c1a39c6edf9 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png new file mode 100644 index 0000000000000000000000000000000000000000..4558b332925757d97d70ee57182c260804629346 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png new file mode 100644 index 0000000000000000000000000000000000000000..9b35e8e0fc4bb514584813b79e8889cfe65649a7 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png new file mode 100644 index 0000000000000000000000000000000000000000..9e0a95f73b1aec44e6bccd6750a1c9f2815178ee Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/opacity.png b/en/application-dev/reference/arkui-ts/figures/opacity.png new file mode 100644 index 0000000000000000000000000000000000000000..d95114ede941db77cf865d3fab288f602ddcc1d0 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/opacity.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/popup.gif b/en/application-dev/reference/arkui-ts/figures/popup.gif new file mode 100644 index 0000000000000000000000000000000000000000..b32a43bd8fc4ae6416b8402c61e1d8e3b9e694ef Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/popup.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/richText.png b/en/application-dev/reference/arkui-ts/figures/richText.png new file mode 100644 index 0000000000000000000000000000000000000000..65826de750d037a394178b66805a9d1ffdad374e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/richText.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textExp1.png b/en/application-dev/reference/arkui-ts/figures/textExp1.png new file mode 100644 index 0000000000000000000000000000000000000000..15d8410388040337f52a039f946d20f3cc0504fc Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textExp1.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textExp2.png b/en/application-dev/reference/arkui-ts/figures/textExp2.png new file mode 100644 index 0000000000000000000000000000000000000000..f6d1aa365e071f3064e25fe45afa4ce4efcddb65 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textExp2.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md index f1bce5a8cc619c0e72e1bff539b311d355c23755..d7b27a661400b2557de5cf6c710f26b0d00e05a5 100644 --- a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -137,9 +137,9 @@ | Name | Description | | -------- | ---------------------- | | Top | Top edge in the vertical direction. | -| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9. | +| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9. | | Bottom | Bottom edge in the vertical direction. | -| Baseline(deprecated) | Text baseline position in the cross axis direction.
This API is deprecated since API version 9.| +| Baseline(deprecated) | Text baseline position in the cross axis direction.
This API is deprecated since API version 9. | | Start | Start position in the horizontal direction. | | Middle(deprecated) | Center position in the horizontal direction.
This API is deprecated since API version 9. | | End | End position in the horizontal direction. | @@ -249,7 +249,7 @@ | End | The child components are aligned with the end edge of the main axis. The last component is aligned with the main-end, and other components are aligned with the next one.| | SpaceBetween | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The first component is aligned with the main-start, the last component is aligned with the main-end, and the remaining components are distributed so that the space between any two adjacent components is the same.| | SpaceAround | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components.| -| SpaceEvenly | The child components are equally distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between two adjacent components are the same.| +| SpaceEvenly | The child components are evenly distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between any two adjacent components are the same. | ## ItemAlign @@ -355,9 +355,9 @@ | Name | Description | | -------- | -------------------------------------- | -| Clip | Extra-long text is truncated. | +| Clip | Extra-long text is clipped. | | Ellipsis | An ellipsis (...) is used to represent clipped text.| -| None | No truncation or ellipsis is used for extra-long text. | +| None | No clipping or ellipsis is used for extra-long text. | ## TextDecorationType @@ -413,9 +413,9 @@ | Name | Description | | ----------- | -------------------- | -| None | Copy and paste is not allowed. | -| InApp | Intra-application copy and paste is allowed.| -| LocalDevice | Intra-device copy and paste is allowed.| +| None | Copy is not allowed. | +| InApp | Intra-application copy is allowed.| +| LocalDevice | Intra-device copy is allowed.| ## HitTestMode9+ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index 925e02a88bce8e5a9fb13a752e178e422afad645..deb88ab76fc047354169bbaadf95b225775335f0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -8,7 +8,7 @@ The **\** component is used to select or deselect all check boxes ## Child Components -None +Not supported ## APIs @@ -18,8 +18,6 @@ Creates a check box group so that you can select or deselect all check boxes in **Parameters** - - | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | group | string | No| Group name.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index fe13a114dcd9c8407c74c6d6193d232998af4034..8a755a02ff75cf3bcbf44a68cfa64e4898b99c33 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. \ The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.
\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability.| +| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.
\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability. | ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md index a9e80d2923b42027be871830988f5d380f77808f..f000af680f63404ce37e365b777fbe9e03b96b5d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md @@ -9,7 +9,7 @@ The **\** component allows users to select from a set of mutually exclusi ## Child Components -None +Not supported ## APIs diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 66c2850e7450574935e07e7d7cc8244653fab906..da9cd933dea63ae836c5f225d6eaab29c1fbdbf4 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -2,17 +2,15 @@ The **\** component parses and displays HTML text. -> **NOTE** +> **NOTE** > -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions -None ## Child Components -None +Not supported ## APIs @@ -20,9 +18,9 @@ RichText(content:string) **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| content | string | Yes| - | String in HTML format.| +| Name| Type| Mandatory | Description| +| ------- | -------- | ------------- | -------- | +| content | string | Yes | String in HTML format.| ## Events @@ -49,34 +47,38 @@ RichText(content:string) | \ | Used to embed or reference a client-side script, such as JavaScript.| \ | ## Example + You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. + ```ts // xxx.ets @Entry @Component struct RichTextExample { - @State data: string = "

h1 heading

" + - "

h1 italic

" + - "

h1 underlined

" + - "

h2 heading

" + - "

h3 heading

" + - "

Regular paragraph


" + - "
" + - "

Font size: 35px; line height: 45px

" + - "

" + - "

This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.

" + @State data: string = '

h1 heading

' + + '

h1 italic

' + + '

h1 underlined

' + + '

h2 heading

' + + '

h3 heading

' + + '

Regular paragraph


' + + '
' + + '

Font size: 35px; line height: 45px

' + + '

' + + '

This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.

'; build() { - Flex({direction: FlexDirection.Column,alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }){ + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, + justifyContent: FlexAlign.Center }) { RichText(this.data) - .onStart(()=>{ - console.info("RichText onStart") - }) - .onComplete(()=>{ - console.info("RichText onComplete") - }) + .onStart(() => { + console.info('RichText onStart'); + }) + .onComplete(() => { + console.info('RichText onComplete'); + }) } } } ``` + + ![richText](figures/richText.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index 16a2de9bd3026c60ef1ff972133487dc9dd76b3e..354cd00042b8ba46a1cf9a68effc32f792c9f48a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -2,7 +2,7 @@ The **\** component is used to display a piece of textual information. -> **NOTE** +> **NOTE**
> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -26,27 +26,29 @@ Text(content?: string | Resource) In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Description| -| -------- | -------- | -------- | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode of multiple lines of text.
Default value: **TextAlign.Start**| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect. | -| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode. | -| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| -| decoration | {
type: TextDecorationType,
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
} | -| baselineOffset | number \| string | Offset of the text baseline. | -| letterSpacing | number \| string | Letter spacing. | -| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size. | -| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size. | -| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**| +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------- | +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**| +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect.| +| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.| +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: **{
type: TextDecorationType.None,
color: Color.Black
}** | +| baselineOffset | number \| string | Baseline offset of the text. The default value is **0**. | +| letterSpacing | number \| string | Letter spacing. | +| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size. | +| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size. | +| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**| -> **NOTE** +> **NOTE**
> > The **\** component cannot contain both the text and the child component **\**. If both of them exist, only the content in **\** is displayed. ## Example +### Example 1 +Examples of using **textAlign**, **textOverflow**, **maxLines**, and **lineHeight** ```ts // xxx.ets @Entry @@ -54,77 +56,184 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the struct TextExample1 { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { - Text('lineHeight').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text with the line height set This is the text with the line height set This is the text with the line height set.') - .lineHeight(25).fontSize(12).border({ width: 1 }).padding(10) + // Set the horizontal alignment mode for the text. + // Single-line text + Text('textAlign').fontSize(9).fontColor(0xCCCCCC) + Text('TextAlign set to Center.') + .textAlign(TextAlign.Center) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('TextAlign set to Start.') + .textAlign(TextAlign.Start) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('TextAlign set to End.') + .textAlign(TextAlign.End) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') - Text('TextOverflow').fontSize(9).fontColor(0xCCCCCC) - Text('This is the setting of textOverflow to none text content This is the setting of textOverflow to none text content.') + // Multi-line text + Text('This is the text content with textAlign set to Center.') + .textAlign(TextAlign.Center) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with textAlign set to Start.') + .textAlign(TextAlign.Start) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with textAlign set to End.') + .textAlign(TextAlign.End) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + + // Set the display mode when the text is too long. + Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC) + // Clip the text when the value of maxLines is exceeded. + Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.') .textOverflow({ overflow: TextOverflow.None }) - .fontSize(12).border({ width: 1 }).padding(10) - Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to Clip text content.') - .textOverflow({ overflow: TextOverflow.Clip }) - .maxLines(1).fontSize(12).border({ width: 1 }).padding(10) - Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.'.split('').join('\u200B')) + .maxLines(1) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + + // Show an ellipsis (...) when the value of maxLines is exceeded. + Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.'.split('') + .join('\u200B')) .textOverflow({ overflow: TextOverflow.Ellipsis }) - .maxLines(1).fontSize(12).border({ width: 1 }).padding(10) + .maxLines(1) + .fontSize(12) + .border({ width: 1 }) + .padding(10) - Text('decoration').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text content with the decoration set to Underline and the color set to Red.') - .decoration({ type: TextDecorationType.Underline, color: Color.Red }) + Text('lineHeight').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text with the line height set. This is the text with the line height set.') .fontSize(12).border({ width: 1 }).padding(10) - Text('This is the text content with the decoration set to LineThrough and the color set to Red.') - .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }) - .fontSize(12).border({ width: 1 }).padding(10) - Text('This is the text content with the decoration set to Overline and the color set to Red.') - .decoration({ type: TextDecorationType.Overline, color: Color.Red }) + Text('This is the text with the line height set. This is the text with the line height set.') .fontSize(12).border({ width: 1 }).padding(10) + .lineHeight(20) }.height(600).width(350).padding({ left: 35, right: 35, top: 35 }) } } ``` +![textExp1](figures/textExp1.png) -![en-us_image_0000001257138337](figures/en-us_image_0000001257138337.gif) - +### Example 2 +Example of using **decoration**, **baselineOffset**, **letterSpacing**, and **textCase**: ```ts -// xxx.ets @Entry @Component struct TextExample2 { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { + Text('decoration').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text content with the decoration set to LineThrough and the color set to Red.') + .decoration({ + type: TextDecorationType.LineThrough, + color: Color.Red + }) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + + Text('This is the text content with the decoration set to Overline and the color set to Red.') + .decoration({ + type: TextDecorationType.Overline, + color: Color.Red + }) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + + Text('This is the text content with the decoration set to Underline and the color set to Red.') + .decoration({ + type: TextDecorationType.Underline, + color: Color.Red + }) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + // Set the text baseline offset. + Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text content with baselineOffset 0.') + .baselineOffset(0) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with baselineOffset 30.') + .baselineOffset(30) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with baselineOffset -20.') + .baselineOffset(-20) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + // Set the letter spacing. + Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text content with letterSpacing 0.') + .letterSpacing(0) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with letterSpacing 3.') + .letterSpacing(3) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with letterSpacing -1.') + .letterSpacing(-1) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('textCase').fontSize(9).fontColor(0xCCCCCC) Text('This is the text content with textCase set to Normal.') .textCase(TextCase.Normal) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + // Display the text in lowercase. Text('This is the text content with textCase set to LowerCase.') .textCase(TextCase.LowerCase) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + // Display the text in uppercase. Text('This is the text content with textCase set to UpperCase.') .textCase(TextCase.UpperCase) .fontSize(12).border({ width: 1 }).padding(10) - Text('textAlign').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text content with textAlign set to Center.') - .textAlign(TextAlign.Center) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with textAlign set to Start.') - .textAlign(TextAlign.Start) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with textAlign set to End.') - .textAlign(TextAlign.End) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') - - Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text content with baselineOffset set to 10.') - .baselineOffset(10).fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with baselineOffset set to 30.') - .baselineOffset(30).fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with baselineOffset set to -10.') - .baselineOffset(-10).fontSize(12).border({ width: 1 }).padding(10).width('100%') }.height(700).width(350).padding({ left: 35, right: 35, top: 35 }) } } ``` - -![en-us_image_0000001257058391](figures/en-us_image_0000001257058391.gif) +![textExp1](figures/textExp2.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md index eee8ee70f12c7bf07bb30b5741e659d827b0eb0e..ffb479fd90217da2d88543706e2913f5cf04850f 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md @@ -19,7 +19,7 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController | Name | Type | Mandatory | Description | | -------------- | -------- | ------ | --------------------------------------------------------------------------- | | timeZoneOffset | number | No | Time zone offset.
The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8.
For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region. If the set value is not within the valid range, the time zone offset of the current system will be used.
Default value: time zone offset of the current system| -| controller | [TextClockController](#textclockcontroller) | No | Binds a controller to control the status of the **** component.| +| controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **** component. | ## Attributes @@ -31,7 +31,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## Events -In addition to the universal events (ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. | Name | Description | | -------------------------------------------- | ------------------------------------------------------------ | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 1bc12e9014024c9c3fe02f783ca6d65934f98d9f..cc432c20a683e8ae1b81b4772eb9961a8e575935 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -48,14 +48,14 @@ Creates a time picker whose default time range is from 00:00 to 23:59. ## Example -### Time Selector +### Time Picker ```ts // xxx.ets @Entry @Component struct TimePickerExample { - private selectedTime: Date = new Date('7/22/2022 8:00:00') + private selectedTime: Date = new Date('2022-07-22T08:00:00') build() { Column() { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md index 80715dd307dc9164a788de5eda9b073dd1368e42..161072762c3bd658d17c6afea7882a357f58a7af 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md @@ -16,7 +16,7 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.
Default value: **1**| -| direction | SwipeDirection | No| Swipe direction.
Default value: **SwipeDirection.All**| +| direction | [swipeDirection](#swipedirection)| No| Swipe direction.
Default value: **SwipeDirection.All**| | speed | number | No| Minimum speed of the swipe gesture, in vp/s.
Default value: **100**| ## SwipeDirection @@ -24,8 +24,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num | Name| Description| | -------- | -------- | | All | All directions.| -| Horizontal | Horizontal direction.| -| Vertical | Vertical direction.| +| Horizontal | Horizontal direction. The gesture event is triggered when the angle between the finger moving direction and the x-axis is less than 45 degrees.| +| Vertical | Vertical direction. The gesture event is triggered when the angle between the finger moving direction and the y-axis is less than 45 degrees.| | None | Swiping disabled.| @@ -33,9 +33,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num | Name| Description| | -------- | -------- | -| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) => void) | Triggered when a swipe gesture is recognized.| +| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Triggered when a swipe gesture is recognized.| -![en-us_image_0000001231374661](figures/en-us_image_0000001231374661.png) ## Example ```ts @@ -43,27 +42,31 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num @Entry @Component struct SwipeGestureExample { - @State rotateAngle : number = 0 - @State speed : number = 1 + @State rotateAngle: number = 0; + @State speed: number = 1; build() { Column() { - Text("SwipGesture speed : " + this.speed) - Text("SwipGesture angle : " + this.rotateAngle) - } - .position({x: 80, y: 200}) - .border({width:2}) - .width(260).height(260) - .rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) - .gesture( - SwipeGesture({fingers: 1, direction: SwipeDirection.Vertical}) + Column() { + Text("SwipeGesture speed\n" + this.speed) + Text("SwipeGesture angle\n" + this.rotateAngle) + } + .border({ width: 3 }) + .width(300) + .height(200) + .margin(100) + .rotate({ angle: this.rotateAngle }) + // The gesture event is triggered by swiping vertically with one finger. + .gesture( + SwipeGesture({ direction: SwipeDirection.Vertical }) .onAction((event: GestureEvent) => { - this.speed = event.speed - this.rotateAngle = event.angle - }) - ) + this.speed = event.speed; + this.rotateAngle = event.angle; + }) + ) + }.width('100%') } } ``` -![en-us_image_0000001231374559](figures/en-us_image_0000001231374559.gif) + ![en-us_image_0000001231374559.png](figures/en-us_image_0000001231374559.png) diff --git a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 0b89c6f7d39270890a4f3fb97b269ce7bbeb3e2f..d4982a55e1b4b12ecc09658f6cc5af50f4c804d2 100644 --- a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -6,6 +6,8 @@ Use **RenderingContext** to draw rectangles, text, images, and other objects on > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + + ## APIs CanvasRenderingContext2D(setting: RenderingContextSetting) @@ -721,6 +723,7 @@ Draws an outlined rectangle on the canvas. struct StrokeRect { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -764,16 +767,17 @@ Clears the content in a rectangle on the canvas. struct ClearRect { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') + .backgroundColor('#ffffff') .onReady(() =>{ this.context.fillStyle = 'rgb(0,0,255)' - this.context.fillRect(0,0,500,500) - this.context.clearRect(20,20,150,100) + this.context.fillRect(20,20,200,200) + this.context.clearRect(30,30,150,100) }) } .width('100%') @@ -809,6 +813,7 @@ Draws filled text on the canvas. struct FillText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -853,6 +858,7 @@ Draws a text stroke on the canvas. struct StrokeText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -921,6 +927,7 @@ Measures the specified text to obtain its width. This API returns a **TextMetric struct MeasureText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -973,6 +980,8 @@ Strokes a path. .onReady(() =>{ this.context.moveTo(25, 25) this.context.lineTo(25, 105) + this.context.lineTo(75, 105) + this.context.lineTo(75, 25) this.context.strokeStyle = 'rgb(0,0,255)' this.context.stroke() }) @@ -1435,7 +1444,7 @@ Draws an ellipse in the specified rectangular region on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.context.beginPath() - this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) this.context.stroke() }) } @@ -1503,7 +1512,7 @@ Fills the area inside a closed path on the canvas. | Name | Type | Mandatory | Default Value | Description | | -------- | -------------- | ---- | --------- | ---------------------------------------- | -| fillRule | CanvasFillRule | No | "nonzero" | Specifies the rule to populate the object.
The options are **"nonzero"** and **"evenodd"**.| +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| **Example** @@ -1616,11 +1625,11 @@ Sets the current path to a clipping area. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.rect(0, 0, 200, 200) + this.context.rect(0, 0, 100, 200) this.context.stroke() this.context.clip() this.context.fillStyle = "rgb(255,0,0)" - this.context.fillRect(0, 0, 150, 150) + this.context.fillRect(0, 0, 200, 200) }) } .width('100%') @@ -1634,7 +1643,7 @@ Sets the current path to a clipping area. clip(path: Path2D, fillRule?: CanvasFillRule): void -Sets a **Path2D** path to a clipping area. This API is a null API. +Sets the current path to a clipping path. **Parameters** @@ -1644,12 +1653,44 @@ Sets a **Path2D** path to a clipping area. This API is a null API. | fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct Clip { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.rect(80,10,20,130); + region.rect(40,50,100,50); + this.context.clip(region,"evenodd") + this.context.fillStyle = "rgb(255,0,0)" + this.context.fillRect(0, 0, this.context.width, this.context.height) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777779](figures/en-us_image_000000127777779.png) + ### filter filter(filter: string): void -Provides filter effects. This API is a null API. +Provides filter effects. This API is a void API. **Parameters** @@ -1662,21 +1703,21 @@ Provides filter effects. This API is a null API. getTransform(): Matrix2D -Obtains the current transformation matrix being applied to the context. This API is a null API. +Obtains the current transformation matrix being applied to the context. This API is a void API. ### resetTransform resetTransform(): void -Resets the current transform to the identity matrix. This API is a null API. +Resets the current transform to the identity matrix. This API is a void API. ### direction direction(direction: CanvasDirection): void -Sets the current text direction used to draw text. This API is a null API. +Sets the current text direction used to draw text. This API is a void API. ### rotate @@ -1751,9 +1792,10 @@ Scales the canvas based on the given scale factors. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.strokeRect(10, 10, 25, 25) + this.context.lineWidth = 3 + this.context.strokeRect(30, 30, 50, 50) this.context.scale(2, 2) // Scale to 200% - this.context.strokeRect(10, 10, 25, 25) + this.context.strokeRect(30, 30, 50, 50) }) } .width('100%') @@ -1772,6 +1814,7 @@ transform(a: number, b: number, c: number, d: number, e: number, f: number): voi Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects. > **NOTE** +> > The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. > > - x' = scaleX \* x + skewY \* y + translateX @@ -1877,7 +1920,7 @@ Resets the existing transformation matrix and creates a new transformation matri setTransform(transform?: Matrix2D): void -Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. This API is a null API. +Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. This API is a void API. ### translate @@ -1983,7 +2026,7 @@ Draws an image on the canvas. createImageData(sw: number, sh: number): ImageData -Creates an **ImageData** object with the specified dimensions. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions. **Parameters** @@ -1993,23 +2036,21 @@ Creates an **ImageData** object with the specified dimensions. For details, see | sh | number | Yes | 0 | Height of the **ImageData** object.| -### createImageData - createImageData(imageData: ImageData): ImageData -Creates an **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object. **Parameters** | Name | Type | Mandatory | Default Value | Description | | --------- | ---------------------------------------- | ---- | ---- | ----------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object.| +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object.| **Return value** | Type | Description | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| ### getPixelMap @@ -2037,7 +2078,7 @@ Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created wi getImageData(sx: number, sy: number, sw: number, sh: number): ImageData -Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas. +Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas. **Parameters** @@ -2052,7 +2093,39 @@ Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created | Type | Description | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | **ImageData** object.| +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| + + +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct GetImageData { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage(this.img,0,0,130,130); + var imagedata = this.context.getImageData(50,50,130,130); + this.context.putImageData(imagedata,150,150); + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) ### putImageData @@ -2061,13 +2134,13 @@ putImageData(imageData: ImageData, dx: number, dy: number): void putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void -Puts data from the given **[ImageData](ts-components-canvas-imagebitmap.md)** object into the specified rectangular area on the canvas. +Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ----------- | ---------------------------------------- | ---- | ------------ | ----------------------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object with pixels to put onto the canvas. | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object with pixels to put onto the canvas. | | dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | | dy | number | Yes | 0 | Y-axis offset of the rectangular area on the canvas. | | dirtyX | number | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.| @@ -2142,6 +2215,7 @@ Sets the dash line style. .onReady(() =>{ this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) + this.context.stroke() }) } .width('100%') @@ -2165,24 +2239,34 @@ Obtains the dash line style. | -------- | ------------------------ | | number[] | An array of numbers that specify distances to alternately draw a line and a gap.| + **Example** ```ts // xxx.ets - @Entry - @Component - struct GetLineDash { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { +@Entry +@Component +struct CanvasGetLineDash { + @State message: string = 'Hello World' + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + console.error('before getlinedash clicked') + let res = this.context.getLineDash() + console.error(JSON.stringify(res)) + }) Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) + .onReady(() => { this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) this.context.stroke(); @@ -2190,17 +2274,20 @@ Obtains the dash line style. }) } .width('100%') - .height('100%') } + .height('100%') } +} ``` +![en-us_image_000000127777778](figures/en-us_image_000000127777778.png) + ### imageSmoothingQuality imageSmoothingQuality(quality: imageSmoothingQuality) -Sets the quality of image smoothing. This API is a null API. +Sets the quality of image smoothing. This API is a void API. **Parameters** @@ -2220,7 +2307,7 @@ Displays the specified **ImageBitmap** object. | Name | Type | Description | | ------ | ---------------------------------------- | ------------------ | -| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.| +| bitmap | [ImageBitmap](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.| **Example** @@ -2228,7 +2315,7 @@ Displays the specified **ImageBitmap** object. // xxx.ets @Entry @Component - struct PutImageData { + struct TransferFromImageBitmap { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -2259,6 +2346,7 @@ Displays the specified **ImageBitmap** object. ``` ![en-us_image_000000127777773](figures/en-us_image_000000127777773.png) + ### toDataURL toDataURL(type?: string, quality?: number): string @@ -2328,7 +2416,11 @@ Restores the saved drawing context. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.restore() + this.context.save(); // save the default state + this.context.fillStyle = "green"; + this.context.fillRect(20, 20, 100, 100); + this.context.restore(); // restore to the default state + this.context.fillRect(150, 75, 100, 100); }) } .width('100%') @@ -2336,6 +2428,7 @@ Restores the saved drawing context. } } ``` + ![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### save @@ -2361,14 +2454,19 @@ Saves all states of the canvas in the stack. This API is usually called when the .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.save() - }) + this.context.save(); // save the default state + this.context.fillStyle = "green"; + this.context.fillRect(20, 20, 100, 100); + this.context.restore(); // restore to the default state + this.context.fillRect(150, 75, 100, 100); + }) } .width('100%') .height('100%') } } ``` + ![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### createLinearGradient diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md index b073ef589bb007932cca479c1a3bfc84591bde49..a8c3cf662854126929a613d1557c7d2a1025ff91 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md @@ -3,8 +3,9 @@ The **\** component can be used to customize drawings. > **NOTE** -> -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## Required Permissions @@ -37,7 +38,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | ----------------------------- | ---- | -------------------- | | onReady(event: () => void) | - | Triggered when a canvas is ready. When this event is triggered, the width and height of the canvas can be obtained, and you can use the canvas APIs to draw images.| -## Example + +**Example** ```ts // xxx.ets @@ -53,8 +55,8 @@ struct CanvasExample { .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.fillRect(0,30,100,100) + .onReady(() => { + this.context.fillRect(0, 30, 100, 100) }) } .width('100%') @@ -62,3 +64,4 @@ struct CanvasExample { } } ``` + ![en-us_image_0000001194032666](figures/en-us_image_0000001194032666.png) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index 0509567d2ffb8983abc115e92e3d34a881cc8d96..b2ebc714ee127ede15141dffaac3b47914be80c8 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -3,23 +3,27 @@ **CanvasGradient** provides a canvas gradient object. > **NOTE** -> +> > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## addColorStop addColorStop(offset: number, color: string): void Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color. -- Parameters + +**Parameters** + | Name | Type | Mandatory | Default Value | Description | | ------ | ------ | ---- | --------- | ---------------------------- | | offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.| | color | string | Yes | '#ffffff' | Gradient color to set. | -- Example + +**Example** ```ts // xxx.ets @@ -48,10 +52,6 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse .height('100%') }} ``` - - - - ![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md index f5c6527207199c2331afcdd27c0809ad4a62db90..3dd7664d96505f7e18b90071dd25e4cd9eaaf99d 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md @@ -1,19 +1,49 @@ # ImageBitmap -> **NOTE** -> -> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +An **ImageBitmap** object stores pixel data rendered on a canvas. +> **NOTE** +> +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -An **ImageBitmap** object stores pixel data rendered on a canvas. ## Attributes -| Name| Type| Description| +| Name| Type| Description| | -------- | -------- | -------- | -| width | number | Pixel width of the **ImageBitmap** object.| -| height | number | Pixel height of the **ImageBitmap** object.| +| width | number | Pixel width of the **ImageBitmap** object.| +| height | number | Pixel height of the **ImageBitmap** object.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct ImageExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage( this.img,0,0,500,500,0,0,400,200); + }) + } + .width('100%') + .height('100%') + } + } + ``` + + ![en-us_image_0000001194352442](figures/en-us_image_0000001194352442.png) + ## Methods diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md index 6fe18b7ddaca893209a91e9ed9b339c5f8fa45f2..366da1b45bd89edb10affc51e34697d5497b21a5 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md @@ -1,17 +1,48 @@ # ImageData - An **ImageData** object stores pixel data rendered on a canvas. > **NOTE** -> -> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## Attributes -| Name| Type| Description| +| Name| Type| Description| | -------- | -------- | -------- | -| width | number | Actual width of the rectangle on the canvas, in pixels.| -| height | number | Actual height of the rectangle on the canvas, in pixels.| -| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.| +| width | number | Actual width of the rectangle on the canvas, in pixels.| +| height | number | Actual height of the rectangle on the canvas, in pixels.| +| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.| + +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct Translate { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage(this.img,0,0,130,130); + var imagedata = this.context.getImageData(50,50,130,130); + this.context.putImageData(imagedata,150,150); + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md index 77690f350b1b2d4290789c864998cb8ab78a51f9..aacc4d7e663d89abb4020c24d5fc57aaee1d8c56 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md @@ -3,13 +3,10 @@ **Lottie** allows you to implement animation-specific operations. > **NOTE** +> > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions - -None - ## Modules to Import @@ -19,7 +16,7 @@ import lottie from '@ohos/lottieETS' > **NOTE** > -> In the **Terminal** window, run the `npm install @ohos/lottieETS` command to download Lottie. +> In the **Terminal** window, run the `npm install @ohos/lottieETS` command to download Lottie. The download requires the related permission. > > To install an OpenHarmony npm third-party package, run the `npm config set @ohos:registry=https://repo.harmonyos.com/npm/` command to set the repository address. @@ -32,16 +29,17 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea Loads an animation. Before calling this method, declare the **Animator('\__lottie\_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**. -- Parameters - | Name | Type | Mandatory | Description | - | -------------- | --------------------------- | ---- | ---------------------------------------- | - | path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| - | container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| - | render | string | Yes | Rendering type. The value can only be **"canvas"**. | - | loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| - | autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. | - | name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. | - | initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | ---------------------------------------- | +| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| +| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| +| render | string | Yes | Rendering type. The value can only be **"canvas"**. | +| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| +| autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. | +| name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. | +| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | ## lottie.destroy @@ -50,12 +48,13 @@ destroy(name: string): void Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| -- Example +**Example** ```ts // xxx.ets import lottie from '@ohos/lottieETS' @@ -130,12 +129,14 @@ play(name: string): void Plays a specified animation. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| + +**Example** -- Example ```ts lottie.play(this.animateName) ``` @@ -147,12 +148,14 @@ pause(name: string): void Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| + +**Example** -- Example ```ts lottie.pause(this.animateName) ``` @@ -164,12 +167,14 @@ togglePause(name: string): void Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| + +**Example** -- Example ```ts lottie.togglePause(this.animateName) ``` @@ -181,12 +186,14 @@ stop(name: string): void Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | ---------------------------------------- | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| + +**Example** -- Example ```ts lottie.stop(this.animateName) ``` @@ -198,13 +205,15 @@ setSpeed(speed: number, name: string): void Sets the playback speed of the specified animation. -- Parameters - | Name | Type | Mandatory | Description | - | ----- | ------ | ---- | ---------------------------------------- | - | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.| - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| + +**Example** -- Example ```ts lottie.setSpeed(5, this.animateName) ``` @@ -216,13 +225,15 @@ setDirection(direction: AnimationDirection, name: string): void Sets the direction in which the specified animation plays. -- Parameters - | Name | Type | Mandatory | Description | - | --------- | ------------------ | ---- | ---------------------------------------- | - | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1 | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------ | ---- | ---------------------------------------- | +| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1 | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| + +**Example** -- Example ```ts lottie.setDirection(-1, this.animateName) ``` @@ -262,12 +273,14 @@ play(name?: string): void Plays an animation. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| + +**Example** -- Example ```ts this.animateItem.play() ``` @@ -279,12 +292,14 @@ destroy(name?: string): void Destroys an animation. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| + +**Example** -- Example ```ts this.animateItem.destroy() ``` @@ -296,12 +311,14 @@ pause(name?: string): void Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| + +**Example** -- Example ```ts this.animateItem.pause() ``` @@ -313,12 +330,14 @@ togglePause(name?: string): void Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| + +**Example** -- Example ```ts this.animateItem.togglePause() ``` @@ -330,12 +349,14 @@ stop(name?: string): void Stops an animation. When the **play** interface is called next time, the animation is played from the first frame. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------ | ---- | --------------- | - | name | string | No | Name of the target animation. By default, the value is null.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------------- | +| name | string | No | Name of the target animation. By default, the value is null.| + +**Example** -- Example ```ts this.animateItem.stop() ``` @@ -347,12 +368,14 @@ setSpeed(speed: number): void Sets the playback speed of an animation. -- Parameters - | Name | Type | Mandatory | Description | - | ----- | ------ | ---- | ---------------------------------------- | - | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| + +**Example** -- Example ```ts this.animateItem.setSpeed(5); ``` @@ -364,12 +387,14 @@ setDirection(direction: AnimationDirection): void Sets the playback direction of an animation. -- Parameters - | Name | Type | Mandatory | Description | - | --------- | ------------------ | ---- | ---------------------------------------- | - | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1.| +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------ | ---- | ---------------------------------------- | +| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1.| + +**Example** -- Example ```ts this.animateItem.setDirection(-1) ``` @@ -381,14 +406,16 @@ goToAndStop(value: number, isFrame?: boolean): void Sets the animation to stop at the specified frame or time. -- Parameters - | Name | Type | Mandatory | Description | - | ------- | ------- | ---- | ---------------------------------------- | - | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | - | isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.| - | name | string | No | Name of the target animation. By default, the value is null. | +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ---------------------------------------- | +| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | +| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.| +| name | string | No | Name of the target animation. By default, the value is null. | + +**Example** -- Example ```ts // Set the animation to stop at the specified frame. this.animateItem.goToAndStop(25, true) @@ -403,14 +430,16 @@ goToAndPlay(value: number, isFrame: boolean, name?: string): void Sets the animation to start from the specified frame or time progress. -- Parameters - | Name | Type | Mandatory | Description | - | ------- | ------- | ---- | ---------------------------------------- | - | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | - | isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.| - | name | string | No | Name of the target animation. By default, the value is null. | +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ---------------------------------------- | +| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | +| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.| +| name | string | No | Name of the target animation. By default, the value is null. | + +**Example** -- Example ```ts // Set the animation to stop at the specified frame. this.animateItem.goToAndPlay(25, true) @@ -425,13 +454,15 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean Sets the animation to play only the specified segment. -- Parameters - | Name | Type | Mandatory | Description | - | --------- | ---------------------------------------- | ---- | ---------------------------------------- | - | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle.| - | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------------------------- | +| segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle.| +| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | + +**Example** -- Example ```ts // Set the animation to play the specified segment. this.animateItem.playSegments([10, 20], false) @@ -446,12 +477,14 @@ resetSegments(forceFlag: boolean): void Resets the settings configured by the **playSegments** method to play all the frames. -- Parameters - | Name | Type | Mandatory | Description | - | --------- | ------- | ---- | ------------------------------ | - | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.| +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------- | ---- | ------------------------------ | +| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.| + +**Example** -- Example ```ts this.animateItem.resetSegments(true) ``` @@ -463,7 +496,8 @@ resize(): void Resizes the animation layout. -- Example +**Example** + ```ts this.animateItem.resize() ``` @@ -475,12 +509,14 @@ setSubframe(useSubFrame: boolean): void Sets the precision of the **currentFrame** attribute to display floating-point numbers. -- Parameters - | Name | Type | Mandatory | Description | - | ------------ | ------- | ---- | ---------------------------------------- | - | useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.
**true**: The **currentFrame** attribute displays floating-point numbers.
**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------- | ---- | ---------------------------------------- | +| useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.
**true**: The **currentFrame** attribute displays floating-point numbers.
**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.| + +**Example** -- Example ```ts this.animateItem.setSubframe(false) ``` @@ -492,12 +528,14 @@ getDuration(inFrames?: boolean): void Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface. -- Parameters - | Name | Type | Mandatory | Description | - | -------- | ------- | ---- | ---------------------------------------- | - | inFrames | boolean | No | Whether to obtain the duration or number of frames.
**true**: number of frames.
**false**: duration, in ms. The default value is **false**.| +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ---------------------------------------- | +| inFrames | boolean | No | Whether to obtain the duration or number of frames.
**true**: number of frames.
**false**: duration, in ms.
Default value: **false**| + +**Example** -- Example ```ts this.animateItem.getDuration(true) ``` @@ -509,13 +547,15 @@ addEventListener<T = any>(name: AnimationEventName, callback: AnimationEve Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener. -- Parameters - | Name | Type | Mandatory | Description | - | -------- | ------------------------------- | ---- | ---------------------------------------- | - | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| - | callback | AnimationEventCallback<T> | Yes | Custom callback. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ---------------------------------------- | +| name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| +| callback | AnimationEventCallback<T> | Yes | Custom callback. | + +**Example** -- Example ```ts private callbackItem: any = function() { console.log("grunt loopComplete") @@ -533,13 +573,15 @@ removeEventListener<T = any>(name: AnimationEventName, callback?: Animatio Removes an event listener. -- Parameters - | Name | Type | Mandatory | Description | - | -------- | ------------------------------- | ---- | ---------------------------------------- | - | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| - | callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ---------------------------------------- | +| name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| +| callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | + +**Example** -- Example ```ts this.animateItem.removeEventListener('loopComplete', this.animateName) ``` @@ -551,13 +593,15 @@ triggerEvent<T = any>(name: AnimationEventName, args: T): void Directly triggers all configured callbacks of a specified event. -- Parameters - | Name | Type | Mandatory | Description | - | ---- | ------------------ | ---- | --------- | - | name | AnimationEventName | Yes | Animation event type. | - | args | any | Yes | Custom callback parameters.| +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------------------ | ---- | --------- | +| name | AnimationEventName | Yes | Animation event type. | +| args | any | Yes | Custom callback parameters.| + +**Example** -- Example ```ts private triggerCallBack: any = function(item) { console.log("trigger loopComplete, name:" + item.name) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md index 7e30f52d8c730b6ec0527b24d1eeefd31a3c4d91..e8c6fea764e26339c247c5d501f89032d8163dbf 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md @@ -1,11 +1,11 @@ # Path2D -> **NOTE** -> -> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**. +> **NOTE** +> +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**. ## addPath @@ -16,11 +16,11 @@ Adds a path to this path. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| path | path2D | Yes| - | Path to be added to this path.| -| transform | Matrix2D | No| null | Transformation matrix of the new path.| - + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | path | path2D | Yes| - | Path to be added to this path.| + | transform | Matrix2D | No| null | Transformation matrix of the new path.| + **Example** @@ -103,10 +103,10 @@ Moves the current coordinate point of the path to the target point, without draw **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the target point.| -| y | number | Yes| 0 | Y-coordinate of the target point.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the target point.| + | y | number | Yes| 0 | Y-coordinate of the target point.| **Example** @@ -150,10 +150,10 @@ Draws a straight line from the current point to the target point. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the target point.| -| y | number | Yes| 0 | Y-coordinate of the target point.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the target point.| + | y | number | Yes| 0 | Y-coordinate of the target point.| **Example** @@ -198,14 +198,14 @@ Draws a cubic bezier curve on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.| -| cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.| -| cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.| -| cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.| -| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| -| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.| + | cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.| + | cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.| + | cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.| + | x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| + | y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| **Example** @@ -226,7 +226,8 @@ Draws a cubic bezier curve on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.path2Db.moveTo(10, 10) - this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20);this.context.stroke(this.path2Db) + this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20) + this.context.stroke(this.path2Db) }) } .width('100%') @@ -246,12 +247,12 @@ Draws a quadratic curve on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.| -| cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.| -| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| -| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.| + | cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.| + | x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| + | y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| **Example** @@ -293,14 +294,14 @@ Draws an arc on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the center point of the arc.| -| y | number | Yes| 0 | Y-coordinate of the center point of the arc.| -| radius | number | Yes| 0 | Radius of the arc.| -| startAngle | number | Yes| 0 | Start radian of the arc.| -| endAngle | number | Yes| 0 | End radian of the arc.| -| counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the center point of the arc.| + | y | number | Yes| 0 | Y-coordinate of the center point of the arc.| + | radius | number | Yes| 0 | Radius of the arc.| + | startAngle | number | Yes| 0 | Start radian of the arc.| + | endAngle | number | Yes| 0 | End radian of the arc.| + | counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.| **Example** @@ -320,7 +321,8 @@ Draws an arc on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.arc(100, 75, 50, 0, 6.28);this.context.stroke(this.path2Db) + this.path2Db.arc(100, 75, 50, 0, 6.28) + this.context.stroke(this.path2Db) }) } .width('100%') @@ -340,13 +342,13 @@ Draws an arc based on the radius and points on the arc. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x1 | number | Yes| 0 | X-coordinate of the first point on the arc.| -| y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.| -| x2 | number | Yes| 0 | X-coordinate of the second point on the arc.| -| y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.| -| radius | number | Yes| 0 | Radius of the arc.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x1 | number | Yes| 0 | X-coordinate of the first point on the arc.| + | y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.| + | x2 | number | Yes| 0 | X-coordinate of the second point on the arc.| + | y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.| + | radius | number | Yes| 0 | Radius of the arc.| **Example** @@ -387,16 +389,16 @@ Draws an ellipse in the specified rectangular region on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the ellipse center.| -| y | number | Yes| 0 | Y-coordinate of the ellipse center.| -| radiusX | number | Yes| 0 | Ellipse radius on the x-axis.| -| radiusY | number | Yes| 0 | Ellipse radius on the y-axis.| -| rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.| -| startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.| -| endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.| -| counterclockwise | number | No| 0 | Whether to draw the ellipse counterclockwise. The value **0** means to draw the ellipse clockwise, and **1** means to draw the ellipse counterclockwise. This parameter is optional. The default value is **0**. | + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the ellipse center.| + | y | number | Yes| 0 | Y-coordinate of the ellipse center.| + | radiusX | number | Yes| 0 | Ellipse radius on the x-axis.| + | radiusY | number | Yes| 0 | Ellipse radius on the y-axis.| + | rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.| + | startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.| + | endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.| + | counterclockwise | number | No| 0 | Whether to draw the ellipse counterclockwise. The value **0** means to draw the ellipse clockwise, and **1** means to draw the ellipse counterclockwise. This parameter is optional. The default value is **0**.| **Example** @@ -408,7 +410,7 @@ Draws an ellipse in the specified rectangular region on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() - + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -416,7 +418,7 @@ Draws an ellipse in the specified rectangular region on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.path2Db.ellipse(200, 200, 50, 100, 0, Math.PI * 1, Math.PI*2) this.context.stroke(this.path2Db) }) } @@ -437,12 +439,12 @@ Creates a rectangle on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.| -| w | number | Yes| 0 | Width of the rectangle.| -| h | number | Yes| 0 | Height of the rectangle.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.| + | y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.| + | w | number | Yes| 0 | Width of the rectangle.| + | h | number | Yes| 0 | Height of the rectangle.| **Example** @@ -462,7 +464,8 @@ Creates a rectangle on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.rect(20, 20, 100, 100);this.context.stroke(this.path2Db) + this.path2Db.rect(20, 20, 100, 100); + this.context.stroke(this.path2Db) }) } .width('100%') diff --git a/en/application-dev/reference/arkui-ts/ts-container-badge.md b/en/application-dev/reference/arkui-ts/ts-container-badge.md index 912f89de44f63e6e3bb896efb5fa64025f4bd115..7d51379bea19538c5e1c5498d2165373331ed924 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/en/application-dev/reference/arkui-ts/ts-container-badge.md @@ -29,7 +29,7 @@ Create a badge. | count | number | Yes| - | Number of notifications.| | position | BadgePosition | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.| | maxCount | number | No| 99 | Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.| -| style | BadgeStyle | Yes| - | Style of the **** component, including the text color, text size, badge color, and badge size.| +| style | BadgeStyle | Yes| - | Style of the **\** component, including the text color, text size, badge color, and badge size.| Method 2: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle}) diff --git a/en/application-dev/reference/arkui-ts/ts-container-flex.md b/en/application-dev/reference/arkui-ts/ts-container-flex.md index 6ef5525a1fc2c0c2f6b079a0c75b302b360b434d..7d6c24e671419edc603a17cdea023878ebc6239d 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/en/application-dev/reference/arkui-ts/ts-container-flex.md @@ -29,8 +29,8 @@ Creates a standard **\** component. | direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\** component, that is, the direction of the main axis. | | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\** component has a single line or multiple lines. | | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\** component along the main axis. | - | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Stretch | Alignment mode of the child components in the **\** component along the cross axis. | - | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.| + | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\** component along the cross axis. | + | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **\** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.| ## Example @@ -240,9 +240,7 @@ struct FlexExample4 { } ``` -![en-us_image_0000001257138371](figures/en-us_image_0000001257138371.jpg) - -![en-us_image_0000001212378426](figures/en-us_image_0000001212378426.gif) +![en-us_image_0000001174422904](figures/en-us_image_0000001174422904.jpg) ```ts // xxx.ets diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index beed8908018fafdcdbc03ec99e8ec54fedad00dc..6a7cb32d7647f0293a0530829cfe071bd089b474 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -10,7 +10,7 @@ The **\** component provides a list container that presents a series of li ## Child Components -This component supports the [\(ts-container-listitem.md) and [\](ts-container-listitemgroup.md) child components. +This component supports the [\](ts-container-listitem.md) and [\](ts-container-listitemgroup.md) child components. ## APIs diff --git a/en/application-dev/reference/arkui-ts/ts-container-row.md b/en/application-dev/reference/arkui-ts/ts-container-row.md index cdd62b8b32f2928375743c23c930e7fe2abcfbc8..d8b0cf68c9a9914d44f121f6d9ac0bb3ffe947c9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-row.md +++ b/en/application-dev/reference/arkui-ts/ts-container-row.md @@ -20,7 +20,7 @@ Row(value?:{space?: number | string }) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| space | string \| number | No| Space between two adjacent child components in the horizontal layout.
Default value: **0**| +| space | string \| number | No| Space between two adjacent child components in the horizontal layout.
Default value: **0**, in vp | ## Attributes @@ -28,7 +28,7 @@ Row(value?:{space?: number | string }) | Name| Type| Description| | -------- | -------- | -------- | | alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | Alignment mode of child components in the vertical direction.
Default value: **VerticalAlign.Center**| -| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the horizontal direction.
FlexAlign.Start | +| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the horizontal direction.
Default value: **FlexAlign.Start** | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md index a9d5a32e480f4d0ad3f4536dc806edd593bda36a..4858f2c37345ea8d074fdd68dae68860a57e20ee 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md +++ b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md @@ -1,15 +1,10 @@ # RowSplit -> **NOTE** -> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - The **\** lays out child components horizontally and inserts a vertical divider between every two child components. - -## Required Permissions - -None +> **NOTE** +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Child Components @@ -24,12 +19,13 @@ RowSplit() ## Attributes -| Name| Type| Description| +| Name| Type| Description| | -------- | -------- | -------- | -| resizeable | boolean | Whether the divider can be dragged. The default value is **false**.| +| resizeable | boolean | Whether the divider can be dragged. The default value is **false**.| > **NOTE** -> Similar to **\**, the divider of **\** can be dragged to a position that just fully holds a component. +> +> Similar to **\**, the divider of **\** can be dragged to a position that just fully holds a component. ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index 9881904bcc8f635930bae6100064243416031442..37ebd29d9ec78398423a8f86c23c21b3bc64afbf 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -6,7 +6,7 @@ The **\** component scrolls the content when the layout size of a compon > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - When nesting a **\** within this component, specify the width and height for the **\** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\**. > - This component can scroll only when the size on the main axis is less than the content size. -> - The prerequisite for the component to rebound is that the component is scrolled. +> - This component can produce a bounce effect only when there is more than one screen of content. ## Child Components @@ -24,11 +24,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | -------------- | ---------------------------------------- | --------- | -| scrollable | ScrollDirection | Scroll direction.
Default value: **ScrollDirection.Vertical**| +| scrollable | [ScrollDirection](#scrolldirection) | Scroll direction.
Default value: **ScrollDirection.Vertical**| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**| -| scrollBarColor | string \| number \| Color | Color of the scrollbar.| +| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.| | scrollBarWidth | string \| number | Width of the scrollbar.| -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**| +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.None**| ## ScrollDirection | Name | Description | @@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Horizontal | Only horizontal scrolling is supported. | | Vertical | Only vertical scrolling is supported. | | None | Scrolling is disabled. | -| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9.| +| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9. | ## Events @@ -104,7 +104,7 @@ Scrolls to the next or previous page. | Name | Type | Mandatory | Description | | --------- | ------- | ---- | ------------------------------ | | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| -| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | +| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | ### currentOffset @@ -161,14 +161,15 @@ Scrolls by the specified amount. ## Example +### Example 1 ```ts // xxx.ets @Entry @Component struct ScrollExample { - scroller: Scroller = new Scroller() - private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; build() { Stack({ alignContent: Alignment.TopStart }) { @@ -186,38 +187,39 @@ struct ScrollExample { }, item => item) }.width('100%') } - .scrollable(ScrollDirection.Vertical) - .scrollBar(BarState.On) - .scrollBarColor(Color.Gray) - .scrollBarWidth(30) + .scrollable(ScrollDirection.Vertical) // The scrollbar scrolls in the vertical direction. + .scrollBar(BarState.On) // The scrollbar is always displayed. + .scrollBarColor(Color.Gray) // Color of the scrollbar. + .scrollBarWidth(30) // Width of the scrollbar. + .edgeEffect(EdgeEffect.None) .onScroll((xOffset: number, yOffset: number) => { - console.info(xOffset + ' ' + yOffset) + console.info(xOffset + ' ' + yOffset); }) .onScrollEdge((side: Edge) => { - console.info('To the edge') + console.info('To the edge'); }) .onScrollEnd(() => { - console.info('Scroll Stop') + console.info('Scroll Stop'); }) - + Button('scroll 150') .onClick(() => { // Click to scroll down to 150.0 vp. - this.scroller.scrollBy(0,150) + this.scroller.scrollBy(0,150); }) .margin({ top: 10, left: 20 }) Button('scroll 100') .onClick(() => { // Click to scroll down by 100.0 vp. - this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) + this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }); }) .margin({ top: 60, left: 20 }) Button('back top') .onClick(() => { // Click to go back to the top. - this.scroller.scrollEdge(Edge.Top) + this.scroller.scrollEdge(Edge.Top); }) .margin({ top: 110, left: 20 }) Button('next page') .onClick(() => { // Click to go to the next page. - this.scroller.scrollPage({ next: true }) + this.scroller.scrollPage({ next: true }); }) .margin({ top: 170, left: 20 }) }.width('100%').height('100%').backgroundColor(0xDCDCDC) @@ -227,14 +229,14 @@ struct ScrollExample { ![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif) - +### Example 2 ```ts @Entry @Component struct NestedScroll { - @State listPosition: number = 0 // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the center of the list, and 2 indicates scrolling to the bottom of the list. - private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - private scroller: Scroller = new Scroller() + @State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle of the list, and 2 indicates scrolling to the bottom of the list. + private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + private scroller: Scroller = new Scroller(); build() { Flex() { @@ -255,18 +257,18 @@ struct NestedScroll { } .width("100%").height("50%").edgeEffect(EdgeEffect.None) .onReachStart(() => { - this.listPosition = 0 + this.listPosition = 0; }) .onReachEnd(() => { - this.listPosition = 2 + this.listPosition = 2; }) .onScrollBegin((dx: number, dy: number) => { if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) { - this.scroller.scrollBy(0, -dy) - return { dxRemain: dx, dyRemain: 0 } + this.scroller.scrollBy(0, -dy); + return { dxRemain: dx, dyRemain: 0 }; } this.listPosition = 1; - return { dxRemain: dx, dyRemain: dy } + return { dxRemain: dx, dyRemain: dy }; }) Text("Scroll Area") diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 9befeb19bfc2ceb801ad82b29d1ce22c9b1db5f1..a2f9888f7fb5f6fc460a838e3db04ddc5b67a7d8 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -40,7 +40,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.
Default value: **SwiperDisplayMode.Stretch**| | cachedCount8+ | number | Number of child components to be cached.
Default value: **1** | | disableSwipe8+ | boolean | Whether to disable the swipe feature.
Default value: **false** | -| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using the API provided by the interpolation calculation module.
Default value: **Curve.Ease**| +| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the interpolation calculation module.
Default value: **Curve.Ease**| | indicatorStyle8+ | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md#resourcecolor),
selectedColor?: [ResourceColor](ts-types.md#resourcecolor)
} | Style of the navigation dots indicator.
\- **left**: distance between the navigation dots indicator and the left edge of the **\** component.
\- **top**: distance between the navigation dots indicator and the top edge of the **\** component.
\- **right**: distance between the navigation dots indicator and the right edge of the **\** component.
\- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\** component.
\- **size**: diameter of the navigation dots indicator.
\- **mask**: whether to enable the mask for the navigation dots indicator.
\- **color**: color of the navigation dots indicator.
\- **selectedColor**: color of the selected navigation dot.| | displayCount8+ | number\|string | Number of elements to display.
Default value: **1** | | effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**| @@ -62,7 +62,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## SwiperController -Controller of the **\** component. You can bind this object to the **** component and use it to control page switching. +Controller of the **\** component. You can bind this object to the **\** component and use it to control page switching. ### showNext diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md index 4119473322b8ea13d46ff31a7d8fe7eb4c95ed14..3eaa86b6d332b7ee7699efc3243da173a01b260e 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -7,7 +7,7 @@ The **\** component is used only in the **\** component. It co > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -## Child Component +## Child Components This component supports only one child component. @@ -23,7 +23,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
> **NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.| +| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. | > **NOTE** > - The **\** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\** component. diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabs.md b/en/application-dev/reference/arkui-ts/ts-container-tabs.md index cf2877be17fa2cf33cb609c061d598a20ac12738..82503cc45bae76b09dd443e1c935ebd877528303 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -2,7 +2,7 @@ The **\** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view. -> **NOTE**
+> **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -54,7 +54,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## Events -In addition to the universal events (ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. | Name| Description| | -------- | -------- | diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md index 9963f4e41348f73d784b2d67aae0f7d2ed375252..a4dad2bb721a0e4db791ae84bed8a660d717b04b 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md @@ -4,7 +4,8 @@ The **\** component is used to draw a straight line. > **NOTE** -> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Required Permissions diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md index 96bedd577f9bdf9431957ddd52735bda35a60808..df5bc74f017aedfc698e85fd88f9e39f00bcb29d 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -89,4 +89,4 @@ struct PathExample { } ``` -![zh-cn_image_0000001219744193](figures/zh-cn_image_0000001219744193.png) +![en-us_image_0000001219744193](figures/en-us_image_0000001219744193.png) diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md index df8578babc490378d574449deccb716d05ec0e45..15b4da37a04970d3cbfcdce429ede77ec46291b8 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md @@ -16,18 +16,18 @@ Not supported Polygon(value?: {width?: string | number, height?: string | number}) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | width | string \| number | No| 0 | Width.| - | height | string \| number | No| 0 | Height.| +**Parameters** +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| width | string \| number | No| 0 | Width.| +| height | string \| number | No| 0 | Height.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Default Value| Mandatory| Description| +| Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | | points | Array<Point> | [] | No| Vertex coordinates of the polygon.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md index 90b1d2a7aa350976b8ce1a6b9bce84ea079fe07f..8475647b5707a180dba18377ee45ae41796b9a69 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md @@ -16,20 +16,20 @@ Not supported Polyline(value?: {width?: string | number, height?: string | number}) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | width | string \| number | No| 0 | Width.| - | height | string \| number | No| 0 | Height.| +**Parameters** +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| width | string \| number | No| 0 | Width.| +| height | string \| number | No| 0 | Height.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Default Value| Mandatory| Description| +| Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | No| List of coordinates that the polyline passes through.| +| points | Array<Point> | [] | No| List of coordinates that the polyline passes through.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md index 9d0dd2d44a9563306e11895e31e7a295093eb407..bb9a06be8dfc2d71663807a7fc9f9cb2cf3529bf 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md @@ -17,24 +17,25 @@ Not supported Rect(value?: {width?: string | number,height?: string | number,radius?: string | number | Array<string | number>} | {width?: string | number,height?: string | number,radiusWidth?: string | number,radiusHeight?: string | number}) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | width | string \| number | No| 0 | Width.| - | height | string \| number | No| 0 | Height.| - | radius | string \| number \| Array<string \| number> | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.| - | radiusWidth | string \| number | No| 0 | Width of the rounded corner.| - | radiusHeight | string \| number | No| 0 | Height of the rounded corner.| +**Parameters** + +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| width | string \| number | No| 0 | Width.| +| height | string \| number | No| 0 | Height.| +| radius | string \| number \| Array<string \| number> | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.| +| radiusWidth | string \| number | No| 0 | Width of the rounded corner.| +| radiusHeight | string \| number | No| 0 | Height of the rounded corner.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Default Value| Mandatory| Description| +| Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| radiusWidth | string \| number | 0 | No| Width of the rounded corner. The width and height are the same when only the width is set.| -| radiusHeight | string \| number | 0 | No| Height of the rounded corner. The width and height are the same only when the height is set.| +| radiusWidth | string \| number | 0 | No| Width of the rounded corner. The width and height are the same when only the width is set.| +| radiusHeight | string \| number | 0 | No| Height of the rounded corner. The width and height are the same only when the height is set.| | radius | string \| number \| Array<string \| number> | 0 | No| Radius of the rounded corner. You can set separate radiuses for four rounded corners.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index ce61ce33769363c5b331ea3f476a1bd7fa4c9d68..1341cc20d871001547be2084eb35a3feb4d026a9 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -21,10 +21,10 @@ This component can contain child components. Shape(value?: PixelMap) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | value | PixelMap | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.| +**Parameters** +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| value | PixelMap | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-gesture-settings.md b/en/application-dev/reference/arkui-ts/ts-gesture-settings.md index 23da0093a624bcae6f17aa2c6c177ed4c283a44f..81a10d89262340b851a66a47c02735c2dd10c006 100644 --- a/en/application-dev/reference/arkui-ts/ts-gesture-settings.md +++ b/en/application-dev/reference/arkui-ts/ts-gesture-settings.md @@ -29,7 +29,7 @@ Use the following attributes to bind gesture recognition to a component. When a | Name| Description| | -------- | -------- | | Normal | The gestures of child components are not masked and are recognized based on the default gesture recognition sequence.| - | IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.
However, the built-in gestures of the child components are not masked. For example, when the child component is a **** component, the built-in sliding gestures can still be triggered.| + | IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.
However, the built-in gestures of the child components are not masked. For example, when the child component is a **\** component, the built-in sliding gestures can still be triggered.| - GestureType diff --git a/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md b/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md deleted file mode 100644 index 029a61c9f47bfb216d507b70845c3fc6877ca697..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md +++ /dev/null @@ -1,277 +0,0 @@ -# Interpolation Calculation - -Interpolation calculation can be implemented to set the animation interpolation curve, which is used to construct the step curve, cubic Bezier curve, and spring curve objects. - -> **NOTE** -> -> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```js -import Curves from '@ohos.curves' -``` - - -## Curves.initCurve9+ - -initCurve(curve?: Curve): ICurve - - -Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve | [Curve](#curve-enums)| No | Curve.Linear | Curve type.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Interpolation object of the curve.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -``` - - -## Curves.stepsCurve9+ - -stepsCurve(count: number, end: boolean): ICurve - - -Constructs a step curve object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end point of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.stepsCurve(9, true) // Create a step curve. -``` - - -## Curves.cubicBezierCurve9+ - -cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve - - -Constructs a third-order Bezier curve object. The curve value must be between 0 and 1. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. -``` - - -## Curves.springCurve9+ - -springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve - - -Constructs a spring curve object. - - -**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| -| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.| - - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.springCurve(100, 1, 228, 30) // Create a spring curve. -``` - - -## ICurve - - -### interpolate - -interpolate(fraction: number): number - - -Calculation function of the interpolation curve. Passing a normalized time parameter to this function returns the current interpolation. - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | -------------------------------------------- | -| fraction | number | Yes | Current normalized time. The value ranges from 0 to 1.| - -**Return value** - -| Type | Description | -| ------ | ------------------------------------ | -| number | The curve interpolation corresponding to the normalized time point is returned.| - -**Example** - -```ts -import Curves from '@ohos.curves' -let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. -``` - - -## Curves.init(deprecated) - -init(curve?: Curve): string - - -Implements initialization to create a curve object based on the input parameter. This API is deprecated since API version 9. Use [Curves.initCurve](#curvesinitcurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve |[Curve](#curve-enums)| No | Curve.Linear | Curve type.| - - -## Curves.steps(deprecated) - -steps(count: number, end: boolean): string - - -Constructs a step curve object. This API is deprecated since API version 9. Use [Curves.stepsCurve](# curvesstepscurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - - -## Curves.cubicBezier(deprecated) - -cubicBezier(x1: number, y1: number, x2: number, y2: number): string - - -Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - - -## Curves.spring(deprecated) - -spring(velocity: number, mass: number, stiffness: number, damping: number): string - - -Constructs a spring curve object. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| -| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.| - - -## Curve - -| Name | Description | -| ------------------- | ---------------------------------------- | -| Linear | The animation speed keeps unchanged. | -| Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.| -| EaseIn | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.| -| EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.| -| EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.| -| FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).| -| LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).| -| FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0).| -| ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).| -| Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).| -| Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).| -| Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).| -| Friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0).| - - -## Example - -```ts -// xxx.ets -import Curves from '@ohos.curves' -@Entry -@Component -struct ImageComponent { - @State widthSize: number = 200 - @State heightSize: number = 200 - build() { - Column() { - Text() - .margin({top:100}) - .width(this.widthSize) - .height(this.heightSize) - .backgroundColor(Color.Red) - .onClick(()=> { - let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0); - this.widthSize = curve.interpolate(0.5) * this.widthSize; - this.heightSize = curve.interpolate(0.5) * this.heightSize; - }) - .animation({duration: 2000 , curve: Curves.stepsCurve(9, true)}) - }.width("100%").height("100%") - } -} -``` -![en-us_image_0000001212058456](figures/en-us_image_0000001212058456.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md b/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md deleted file mode 100644 index 34f1738c2085bd8c77e6c69f43845a37bbc98985..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md +++ /dev/null @@ -1,441 +0,0 @@ -# Matrix Transformation - -Matrix transformation enables you to rotate, scale, skew, or translate an image. - -> **NOTE** -> -> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```ts -import matrix4 from '@ohos.matrix4' -``` - - -## matrix4.init - -init(array: Array<number>): Matrix4Transit - - -Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------- | ---- | ------------------------------------------------------------ | -| array | Array<number> | Yes | A number array whose length is 16 (4 x 4). For details, see **array**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | 4x4 matrix object created based on the input parameter.| - -**array** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------------- | -| m00 | number | Yes | Scaling value of the x-axis. Defaults to **1** for the identity matrix. | -| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. | -| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. | -| m03 | number | Yes | Meaningless. | -| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. | -| m11 | number | Yes | Scaling value of the y-axis. Defaults to **1** for the identity matrix. | -| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. | -| m13 | number | Yes | Meaningless. | -| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. | -| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. | -| m22 | number | Yes | Scaling value of the z-axis. Defaults to **1** for the identity matrix. | -| m23 | number | Yes | Meaningless. | -| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the identity matrix.| -| m31 | number | Yes | Translation value of the y-axis, in px. Defaults to **0** for the identity matrix.| -| m32 | number | Yes | Translation value of the z-axis, in px. Defaults to **0** for the identity matrix.| -| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. | - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// Create a 4x4 matrix. -let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix) - } - } -} -``` - - -## matrix4.identity - -identity(): Matrix4Transit - - -Matrix initialization function. Can return an identity matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------- | -| Matrix4Transit | Identity matrix object.| - -**Example** - -```ts -// The effect of matrix 1 is the same as that of matrix 2. -import matrix4 from '@ohos.matrix4' -let matrix1 = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -let matrix2 = matrix4.identity() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix1) - Image($r("app.media.zh")) - .width("40%") - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -## matrix4.copy - -copy(): Matrix4Transit - - -Matrix copy function, which is used to copy the current matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------------- | -| Matrix4Transit | Copy object of the current matrix.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = Matrix4.identity().translate({x:100}) - private matrix2 = this.matrix1.copy().scale({x:2}) - - build() { - Column() { - Image($r("app.media.bg1")) - .width("40%") - .height(100) - .transform(this.matrix1) - Image($r("app.media.bg2")) - .width("40%") - .height(100) - .margin({top:50}) - .transform(this.matrix2) - } - } -} -``` - -![en-us_image_0000001256858419](figures/en-us_image_0000001256858419.png) - - -## Matrix4 - - -### combine - -combine(matrix: Matrix4): Matrix4Transit - - -Matrix overlay function, which is used to overlay the effects of two matrices to generate a new matrix object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------ | -| matrix | Matrix4 | Yes | Matrix object to be overlaid.| - -**Return value** - -| Type | Description | -| -------------- | ------------------ | -| Matrix4Transit | Object after matrix overlay.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:200}).copy() - private matrix2 = matrix4.identity().scale({x:2}).copy() - - build() { - Column() { - // Before matrix transformation - Image($r("app.media.icon")) - .width("40%") - .height(100) - .margin({top:50}) - // Translate the x-axis by 200px, and then scale down the x-axis twice. - Image($r("app.media.icon")) - .transform(this.matrix1.combine(this.matrix2)) - .width("40%") - .height(100) - .margin({top:50}) - } - } -} -``` - -![en-us_image_0000001212378428](figures/en-us_image_0000001212378428.png) - - -### invert - -invert(): Matrix4Transit - - -Matrix inverse function. Can return an inverse matrix of the current matrix object, that is, get an opposite effect. - -**Return value** - -| Type | Description | -| -------------- | ---------------------- | -| Matrix4Transit | Inverse matrix object of the current matrix.| - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x). -let matrix1 = matrix4.identity().scale({x:2}) -let matrix2 = matrix1.invert() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width(200) - .height(100) - .transform(matrix1) - .margin({ top: 100 }) - Image($r("app.media.zh")) - .width(200) - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -### translate - -translate({x?: number, y?: number, z?: number}): Matrix4Transit - - -Matrix translation function, which is used to add the translation effect to the x, y, and z axes of the current matrix. - -**Parameter** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------- | -| x | number | No | Translation distance of the x-axis, in px.
Default value: **0**| -| y | number | No | Translation distance of the y-axis, in px.
Default value: **0**| -| z | number | No | Translation distance of the z-axis, in px.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the translation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:100, y:200, z:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![en-us_image_0000001212058494](figures/en-us_image_0000001212058494.png) - - -### scale - -scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Matrix4Transit - - -Matrix scaling function, which is used to add the scaling effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | Scaling multiple of the x-axis.
Default value: **1** | -| y | number | No | Scaling multiple of the y-axis.
Default value: **1** | -| z | number | No | Scaling multiple of the z-axis.
Default value: **1** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the scaling effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![zh-cn_image_0000001219864131](figures/zh-cn_image_0000001219864131.png) - - -### rotate - -rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Matrix4Transit - - -Matrix rotation function, which is used to add the rotation effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | X coordinate of the rotation axis vector.
Default value: **1** | -| y | number | No | Y coordinate of the rotation axis vector.
Default value: **1** | -| z | number | No | Z coordinate of the rotation axis vector.
Default value: **1** | -| angle | number | No | Rotation angle.
Default value: **0** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the rotation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - }.width("100%").margin({top:50}) - } -} -``` - -![en-us_image_0000001211898504](figures/en-us_image_0000001211898504.png) - - -### transformPoint - -transformPoint(point: Point): Point - - -Matrix point transformation function, which is used to apply the current transformation effect to a coordinate point. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----- | ---- | ------------------ | -| point | Point | Yes | Point to be transformed.| - -**Return value** - -| Type | Description | -| ----- | ---------------- | -| Point | Point object after matrix transformation| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -import prompt from '@system.prompt' - -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().transformPoint([100, 10]) - - build() { - Column() { - Button("get Point") - .onClick(() => { - prompt.showToast({message:JSON.stringify(this.matrix1),duration:2000}) - }).backgroundColor(0x2788D9) - }.width("100%").padding(50) - } -} -``` - -![en-us_image_0000001212218464](figures/en-us_image_0000001212218464.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index 2fe2e87870ad855044790259a8709986120d3244..457fbe710bf5c28a0e9d94b9a25737d806cc08f3 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -24,9 +24,9 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P | Name | Type | Mandatory| Description | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string \| [Resource](ts-types.md#resource) | No | Path of the video source, which can be a local path or a URL.
The video resources can be stored in the **video** or **rawfile** folder under **resources**.
The path can include a **dataability://** prefix, which is used to access the video path provided by a Data ability. For details about the path, see [Data Ability Development](../../ability/fa-dataability.md).
**NOTE**
The supported video formats are MP4, MKV, WebM, and TS. | +| src | string \| [Resource](ts-types.md) | No | Path of the video source, which can be a local path or a URL.
The video resources can be stored in the **video** or **rawfile** folder under **resources**.
The path can include a **dataability://** prefix, which is used to access the video path provided by a Data ability. For details about the path, see [Data Ability Development](../../ability/fa-dataability.md).
**NOTE**
The supported video formats are MP4, MKV, WebM, and TS. | | currentProgressRate | number \| string \| PlaybackSpeed8+ | No | Video playback speed.
**NOTE**
The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**.
Default value: **1.0** \| PlaybackSpeed.Speed_Forward_1_00_X | -| previewUri | string \| PixelMap8+ \| [Resource](ts-types.md#resource) | No | Path of the preview image. | +| previewUri | string \| PixelMap8+ \| [Resource](ts-types.md) | No | Path of the preview image. | | controller | [VideoController](#videocontroller) | No | Controller. | ## PlaybackSpeed8+ @@ -53,7 +53,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## Events -In addition to the universal events (ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | @@ -70,7 +70,7 @@ In addition to the universal events (ts-universal-events-click.md), the followin ## VideoController -A **VideoController** object can control one or more videos. +Defines a **VideoController** object to control one or more videos. ### Objects to Import diff --git a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md index e6e19c44e7387dfb6682a9a296a461df72566b21..63f0e8300b8530cc0e7404cfb881ba3eff5d5d03 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md @@ -28,10 +28,10 @@ Defines and shows the action sheet. | confirm | {
value: string \| [Resource](ts-types.md#resource),
action: () => void
} | No | Text content of the confirm button and callback upon button clicking.
Default value:
**value**: button text.
**action**: callback upon button clicking.| | cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked. | | alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| -| offset | {
dx: Length,
dy: Length
} | No | Offset of the dialog box relative to the alignment position.{
dx: 0,
dy: 0
} | +| offset | {
dx: Length,
dy: Length
} | No | Offset of the dialog box relative to the alignment position.
Default value: **{
dx: 0,
dy: 0
}** | | sheets | Array<SheetInfo> | Yes | Options in the dialog box. Each option supports the image, text, and callback.| -## SheetInfo parameters +## SheetInfo | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ----------------- | diff --git a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index 5754a1b194653e4df5afde37bf50b815e14ce2e2..e8488281d24a6b93a24e2fbfceafccba5a657e4e 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -6,11 +6,6 @@ A date picker dialog box is a dialog box that allows users to select a date from > > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. - -## Required Permissions - -None - ## DatePickerDialog.show show(options?: DatePickerDialogOptions) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-menu.md b/en/application-dev/reference/arkui-ts/ts-methods-menu.md index b019c06841a6e94017a9b167b438d5ff90411354..4400e9cbf87afc5854228a1b25a6d74fcf44fd8f 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-menu.md @@ -1,21 +1,16 @@ # Menu -The menu bound to a component through [bindContextMenu](./ts-universal-attributes-menu.md#atrributes) on a page can be closed as needed. +The menu bound to a component through [bindContextMenu](./ts-universal-attributes-menu.md#attributes) on a page can be closed as needed. > **NOTE** > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions - -None - - ## ContextMenu.close |Name|Description| |----|---| -| close(): void | Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#atrributes) on a page.| +| close(): void | Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#attributes) on a page. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index f575385cdac4842a96f03b6516ec40f6bb4c8699..87d6cdb9909b8fb118cebcdfe923bfaffc4544c4 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -6,11 +6,6 @@ A text picker dialog box is a dialog box that allows users to select text from t > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - -## Required Permissions - -None - ## TextPickerDialog.show show(options?: TextPickerDialogOptions) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 2c0d95f5d73e36376cbc44ef7a76d2e234e1bd3c..ba8f9a55944e12d1693f0e82ac91c282a373e814 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -1,15 +1,10 @@ # Time Picker Dialog Box -A time picker dialog box is a dialog box that allows users to select a time from the given range, which is from 00:00 to 23:59 by default. +A time picker dialog box is a dialog box that allows users to select a time from the 24-hour range. > **NOTE** > -> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. - - -## Required Permissions - -None +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. ## TimePickerDialog.show @@ -18,71 +13,63 @@ show(options?: TimePickerDialogOptions) Shows a time picker dialog box. - TimePickerDialogOptions - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | selected | Date | No| Current system time| Time of the selected item.| - | useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| - | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.| - | onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.| - | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.| + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | selected | Date | No| Selected time.
Default value: current system time| + | useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.
Default value: **false**| + | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| + | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| + | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.| ## Example -### Time Picker Sample Code (24-Hour Clock) ```ts // xxx.ets @Entry @Component -struct TimePickerDialogExample01 { - @State isUseMilitaryTime: boolean = true +struct TimePickerDialogExample { + private selectTime: Date = new Date('2020-12-25T08:30:00') build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("TimePickerDialog").onClick(() => { - TimePickerDialog.show({ - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: TimePickerResult) => { - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("TimePickerDialog:onCancel()") - }, - onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) - } + Column() { + Button ("TimePickerDialog 12-hour format") + .margin(20) + .onClick(() => { + TimePickerDialog.show({ + selected: this.selectTime, + onAccept: (value: TimePickerResult) => { + //Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time. + this.selectTime.setHours(value.hour, value.minute) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()"); + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + } + }) }) - }) - } - } -} -``` -### Time Picker Sample Code (12-Hour Clock) -```ts -// xxx.ets -@Entry -@Component -struct TimePickerDialogExample02 { - @State isUseMilitaryTime: boolean = false - - build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("TimePickerDialog").onClick(() => { - TimePickerDialog.show({ - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: TimePickerResult) => { - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("TimePickerDialog:onCancel()") - }, - onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) - } + Button ("TimePickerDialog 24-hour format") + .margin(20) + .onClick(() => { + TimePickerDialog.show({ + selected: this.selectTime, + useMilitaryTime: true, + onAccept: (value: TimePickerResult) => { + this.selectTime.setHours(value.hour, value.minute) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()"); + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + } + }) }) - }) - } + }.width('100%') } } ``` diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 8fc5a51f8ce0dfa8f141d000348257dae7fddfd9..5b082bc803d6d82e93c273fc1ea9ba4ddfd25ce1 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -2,47 +2,46 @@ Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency. - > **NOTE** -> +> > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## APIs OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings) **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------- | ---------------------------------------- | ---- | ---- | ------------------------------ | -| width | number | Yes | - | Width of the offscreen canvas. | -| height | number | Yes | - | Height of the offscreen canvas. | -| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | - | See RenderingContextSettings.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------ | +| width | number | Yes | Width of the offscreen canvas. | +| height | number | Yes | Height of the offscreen canvas. | +| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | See RenderingContextSettings.| ## Attributes -| Name | Type | Description | -| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.
- When the type is **\**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineWidth](#linewidth) | number | Line width. | -| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
- Default value: **'butt'** | -| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
- Default value: **'miter'** | -| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
- Default value: **10** | -| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'** | -| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
**NOTE**
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
- Default value: **'left'** | -| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
- Default value: **'alphabetic'** | -| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | -| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
- Default value: **0.0** | -| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
- Default value: **'source-over'** | -| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
- Default value: **0.0** | -| [shadowColor](#shadowcolor) | string | Shadow color. | -| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | -| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
- Default value: **true** | -| imageSmoothingQuality | string | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**.
- Default value: **'low'** | +| Name | Type | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.
- When the type is **string**, this attribute indicates the color of the filling area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineWidth](#linewidth) | number | Line width. | +| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
- Default value: **'butt'**| +| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
- Default value: **'miter'**| +| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
- Default value: **10**| +| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'**| +| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
> **NOTE**
> In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
- Default value: **'left'**| +| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
- Default value: **'alphabetic'**| +| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | +| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
- Default value: **0.0**| +| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
- Default value: **'source-over'**| +| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
- Default value: **0.0**| +| [shadowColor](#shadowcolor) | string | Shadow color. | +| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | +| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
- Default value: **true**| > **NOTE** > @@ -574,8 +573,7 @@ struct ShadowColor { this.offContext.shadowColor = 'rgb(0,0,255)' this.offContext.fillStyle = 'rgb(255,0,0)' this.offContext.fillRect(30, 30, 100, 100) - var image = this.offContext.transferToImageBitmap -() + var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -769,6 +767,7 @@ Draws an outlined rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -815,6 +814,7 @@ Clears the content in a rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -823,8 +823,8 @@ Clears the content in a rectangle on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(0,0,500,500) - this.offContext.clearRect(20,20,150,100) + this.offContext.fillRect(20,20,200,200) + this.offContext.clearRect(30,30,150,100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -846,12 +846,12 @@ Draws filled text on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | --------------- | -| text | string | Yes | "" | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width allowed for the text.| +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | "" | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width allowed for the text. | **Example** @@ -863,6 +863,7 @@ Draws filled text on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -893,12 +894,12 @@ Draws a text stroke on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | --------------- | -| text | string | Yes | "" | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width of the text to be drawn.| +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | "" | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width of the text to be drawn. | **Example** @@ -910,6 +911,7 @@ Draws a text stroke on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -950,12 +952,12 @@ Returns a **TextMetrics** object used to obtain the width of specified text. | ----------- | ------- | | TextMetrics | **TextMetrics** object.| -**TextMetrics** +**TextMetrics** attributes -| Name | Type | Description | -| ----- | ------ | ------- | -| width | number | Width of the text.| -| height | number | Height of the text.| +| Name | Type | Description | +| ------------------------ | ------ | ---------------------------------------- | +| width | number | Width of the text. | +| height | number | Height of the text. | | actualBoundingBoxAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the bounding rectangle used to render the text. The current value is **0**.| | actualBoundingBoxDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the bounding rectangle used to render the text. The current value is **0**.| | actualBoundingBoxLeft | number | Distance parallel to the baseline from the alignment point determined by the **CanvasRenderingContext2D.textAlign** attribute to the left side of the bounding rectangle of the text. The current value is **0**.| @@ -978,6 +980,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1014,7 +1017,7 @@ Strokes a path. | path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.| **Example** - + ```ts // xxx.ets @Entry @@ -1023,6 +1026,7 @@ Strokes a path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1032,6 +1036,8 @@ Strokes a path. .onReady(() =>{ this.offContext.moveTo(25, 25) this.offContext.lineTo(25, 105) + this.offContext.lineTo(75, 105) + this.offContext.lineTo(75, 25) this.offContext.strokeStyle = 'rgb(0,0,255)' this.offContext.stroke() var image = this.offContext.transferToImageBitmap() @@ -1063,6 +1069,7 @@ Creates a drawing path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1112,6 +1119,7 @@ Moves a drawing path to a target position on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1159,6 +1167,7 @@ Connects the current point to a target position using a straight line. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1199,6 +1208,7 @@ Draws a closed path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1240,9 +1250,9 @@ Creates a pattern for image filling based on a specified source image and repeti **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| +| Type | Description | +| ------------------------------- | ----------------------- | +| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| **Example** @@ -1255,6 +1265,7 @@ Creates a pattern for image filling based on a specified source image and repeti private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1305,6 +1316,7 @@ Draws a cubic bezier curve on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1354,6 +1366,7 @@ Draws a quadratic curve on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1386,13 +1399,13 @@ Draws an arc on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------------- | ------- | ---- | ----- | ---------- | -| x | number | Yes | 0 | X-coordinate of the center point of the arc.| -| y | number | Yes | 0 | Y-coordinate of the center point of the arc.| -| radius | number | Yes | 0 | Radius of the arc. | -| startAngle | number | Yes | 0 | Start radian of the arc. | -| endAngle | number | Yes | 0 | End radian of the arc. | +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ----- | ---------- | +| x | number | Yes | 0 | X-coordinate of the center point of the arc.| +| y | number | Yes | 0 | Y-coordinate of the center point of the arc.| +| radius | number | Yes | 0 | Radius of the arc. | +| startAngle | number | Yes | 0 | Start radian of the arc. | +| endAngle | number | Yes | 0 | End radian of the arc. | | counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.| **Example** @@ -1405,6 +1418,7 @@ Draws an arc on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1454,6 +1468,7 @@ Draws an arc based on the radius and points on the arc. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1485,15 +1500,15 @@ Draws an ellipse in the specified rectangular region on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------------- | ------- | ---- | ----- | ----------------- | -| x | number | Yes | 0 | X-coordinate of the ellipse center. | -| y | number | Yes | 0 | Y-coordinate of the ellipse center. | -| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | -| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | -| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | -| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| -| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ----- | ----------------- | +| x | number | Yes | 0 | X-coordinate of the ellipse center. | +| y | number | Yes | 0 | Y-coordinate of the ellipse center. | +| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | +| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | +| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | +| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| +| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| | counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. | **Example** @@ -1514,7 +1529,7 @@ Draws an ellipse in the specified rectangular region on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.beginPath() - this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -1537,12 +1552,12 @@ Creates a rectangle on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ------------- | -| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| -| w | number | Yes | 0 | Width of the rectangle. | -| h | number | Yes | 0 | Height of the rectangle. | +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | ------------- | +| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| +| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| +| w | number | Yes | 0 | Width of the rectangle. | +| h | number | Yes | 0 | Height of the rectangle. | **Example** @@ -1554,6 +1569,7 @@ Creates a rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1578,11 +1594,15 @@ Creates a rectangle on the canvas. ### fill -fill(): void +fill(fillRule?: CanvasFillRule): void Fills the area inside a closed path on the canvas. - **Example** +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| ```ts // xxx.ets @@ -1592,6 +1612,7 @@ Fills the area inside a closed path on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1614,12 +1635,73 @@ Fills the area inside a closed path on the canvas. ![en-us_image_0000001256858421](figures/en-us_image_0000001256858421.png) +fill(path: Path2D, fillRule?: CanvasFillRule): void + +Fills the area inside a closed path on the canvas. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | Yes | | A **Path2D** path to fill. | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| + + +**Example** + +```ts +// xxx.ets +@Entry +@Component +struct Fill { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.moveTo(30, 90); + region.lineTo(110, 20); + region.lineTo(240, 130); + region.lineTo(60, 130); + region.lineTo(190, 20); + region.lineTo(270, 90); + region.closePath(); + // Fill path + this.offContext.fillStyle = 'green'; + this.offContext.fill(region, "evenodd"); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} +``` + + ![en-us_image_000000127777775](figures/en-us_image_000000127777775.png) + + + ### clip -clip(): void +clip(fillRule?: CanvasFillRule): void Sets the current path to a clipping path. +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| + **Example** ```ts @@ -1630,6 +1712,7 @@ Sets the current path to a clipping path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1637,11 +1720,11 @@ Sets the current path to a clipping path. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rect(0, 0, 200, 200) + this.offContext.rect(0, 0, 100, 200) this.offContext.stroke() this.offContext.clip() this.offContext.fillStyle = "rgb(255,0,0)" - this.offContext.fillRect(0, 0, 150, 150) + this.offContext.fillRect(0, 0, 200, 200) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1655,6 +1738,89 @@ Sets the current path to a clipping path. ![en-us_image_0000001257058441](figures/en-us_image_0000001257058441.png) +clip(path:Path2D, fillRule?: CanvasFillRule): void + +Sets a closed path to a clipping path. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | Yes | | A **Path2D** path to clip.| +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| + + **Example** + + ```ts + // xxx.ets +@Entry +@Component +struct Clip { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.rect(80,10,20,130); + region.rect(40,50,100,50); + this.offContext.clip(region,"evenodd") + this.offContext.fillStyle = "rgb(255,0,0)" + this.offContext.fillRect(0, 0, 600, 600) + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777779](figures/en-us_image_000000127777779.png) + + + +### filter + +filter(filter: string): void + +Sets a filter for the image on the canvas. This API is a void API. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ------ | ------ | ---- | ---- | ------------ | +| filter | string | Yes | - | Functions that accept various filter effects.| + + +### getTransform + +getTransform(): Matrix2D + +Obtains the current transformation matrix being applied to the context. This API is a void API. + + +### resetTransform + +resetTransform(): void + +Resets the current transform to the identity matrix. This API is a void API. + + +### direction + +direction(direction: CanvasDirection): void + +Sets the text direction for drawing text. This API is a void API. + + ### rotate rotate(angle: number): void @@ -1663,8 +1829,8 @@ Rotates a canvas clockwise around its coordinate axes. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | +| Name | Type | Mandatory | Default Value | Description | +| ----- | ------ | ---- | ---- | ---------------------------------------- | | angle | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.| **Example** @@ -1677,6 +1843,7 @@ Rotates a canvas clockwise around its coordinate axes. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1722,6 +1889,7 @@ Scales the canvas based on scale factors. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1729,9 +1897,10 @@ Scales the canvas based on scale factors. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.lineWidth = 3 + this.offContext.strokeRect(30, 30, 50, 50) this.offContext.scale(2, 2) // Scale to 200% - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.strokeRect(30, 30, 50, 50) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1761,14 +1930,14 @@ Defines a transformation matrix. To transform a graph, you only need to set para **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---------- | ------ | ---- | ---- | -------- | -| a | number | Yes | 0 |X-axis scale.| -| b | number | Yes | 0 |X-axis skew.| -| c | number | Yes | 0 |Y-axis skew.| -| d | number | Yes | 0 |Y-axis scale.| -| e | number | Yes | 0 |X-axis translation.| -| f | number | Yes | 0 |Y-axis translation.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | -------------------- | +| a | number | Yes | 0 | X-axis scale. | +| b | number | Yes | 0 | X-axis skew. | +| c | number | Yes | 0 | Y-axis skew. | +| d | number | Yes | 0 | Y-axis scale. | +| e | number | Yes | 0 | X-axis translation.| +| f | number | Yes | 0 | Y-axis translation.| **Example** @@ -1780,6 +1949,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1812,18 +1982,18 @@ Defines a transformation matrix. To transform a graph, you only need to set para setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void -Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. +Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | -| ---------- | ------ | ---- | ---- | -------- | -| a | number | Yes | 0 |X-axis scale.| -| b | number | Yes | 0 |X-axis skew.| -| c | number | Yes | 0 |Y-axis skew.| -| d | number | Yes | 0 |Y-axis scale.| -| e | number | Yes | 0 |X-axis translation.| -| f | number | Yes | 0 |Y-axis translation.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | -------------------- | +| a | number | Yes | 0 | X-axis scale. | +| b | number | Yes | 0 | X-axis skew. | +| c | number | Yes | 0 | Y-axis skew. | +| d | number | Yes | 0 | Y-axis scale. | +| e | number | Yes | 0 | X-axis translation.| +| f | number | Yes | 0 | Y-axis translation.| **Example** @@ -1835,6 +2005,7 @@ Resets the existing transformation matrix and creates a new transformation matri private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1857,8 +2028,10 @@ Resets the existing transformation matrix and creates a new transformation matri } ``` - ![zh-cn_image_0000001193872526](figures/zh-cn_image_0000001193872526.png) + ![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png) + +### translate ### translate @@ -1868,7 +2041,7 @@ Moves the origin of the coordinate system. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | -------- | | x | number | Yes | 0 | X-axis translation.| | y | number | Yes | 0 | Y-axis translation.| @@ -1883,6 +2056,7 @@ Moves the origin of the coordinate system. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1903,7 +2077,7 @@ Moves the origin of the coordinate system. } ``` - ![en-us_image_0000001256978373](figures/en-us_image_0000001256978373.png) + ![en-us_image_0000001238832413](figures/en-us_image_0000001238832413.png) ### drawImage @@ -1918,17 +2092,17 @@ Draws an image on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------- | ---------------------------------------- | ---- | ---- | -------------------- | -| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.| -| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image.| -| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image.| -| sw | number | No | 0 | Target width to crop the source image. | -| sh | number | No | 0 | Target height to crop the source image. | -| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | -| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas.| -| dw | number | No | 0 | Width of the drawing area. | -| dh | number | No | 0 | Height of the drawing area. | +| Name | Type | Mandatory | Default Value | Description | +| ----- | ---------------------------------------- | ---- | ---- | ----------------------------- | +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.| +| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sw | number | No | 0 | Target width to crop the source image. | +| sh | number | No | 0 | Target height to crop the source image. | +| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | +| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. | +| dw | number | No | 0 | Width of the drawing area. | +| dh | number | No | 0 | Height of the drawing area. | **Example** @@ -1937,7 +2111,7 @@ Draws an image on the canvas. // xxx.ets @Entry @Component - struct Index { + struct DrawImage { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") @@ -1967,33 +2141,31 @@ Draws an image on the canvas. createImageData(sw: number, sh: number): ImageData -Creates an **ImageData** object based on the width and height. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ------------- | -| sw | number | Yes | 0 | Width of the **ImageData** object.| -| sh | number | Yes | 0 | Height of the **ImageData** object.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | ------------- | +| sw | number | Yes | 0 | Width of the **ImageData** object.| +| sh | number | Yes | 0 | Height of the **ImageData** object.| -### createImageData - createImageData(imageData: ImageData): ImageData -Creates an **ImageData** object based on the given existing **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object by copying an existing **ImageData** object. **Parameters** | Name | Type | Mandatory | Default Value | Description | | --------- | ---------------------------------------- | ---- | ---- | ---------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy.| +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object to copy.| **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| Type | Description | +| ---------------------------------------- | ------------- | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| ### getPixelMap @@ -2003,29 +2175,29 @@ Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created wi **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| sx | number | Yes| 0 | X-coordinate of the upper left corner of the output area.| -| sy | number | Yes| 0 | Y-coordinate of the upper left corner of the output area.| -| sw | number | Yes| 0 | Width of the output area.| -| sh | number | Yes| 0 | Height of the output area.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | --------------- | +| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| +| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| +| sw | number | Yes | 0 | Width of the output area. | +| sh | number | Yes | 0 | Height of the output area. | **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.| +| Type | Description | +| ---------------------------------------- | ------------ | +| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.| ### getImageData getImageData(sx: number, sy: number, sw: number, sh: number): ImageData -Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas. +Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | --------------- | | sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| | sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| @@ -2034,9 +2206,44 @@ Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| Type | Description | +| ---------------------------------------- | ------------- | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| + + +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct GetImageData { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.drawImage(this.img,0,0,130,130); + var imagedata = this.offContext.getImageData(50,50,130,130); + this.offContext.putImageData(imagedata,150,150); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) ### putImageData @@ -2045,11 +2252,11 @@ putImageData(imageData: Object, dx: number, dy: number): void putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth?: number, dirtyHeight: number): void -Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular area on the canvas. +Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ----------- | ------ | ---- | ------------ | ----------------------------- | | imagedata | Object | Yes | null | **ImageData** object with pixels to put onto the canvas. | | dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | @@ -2104,8 +2311,8 @@ Sets the dash line style. **Parameters** -| Parameter | Type | Description | -| -------- | ----- | -------------------- | +| Name | Type | Description | +| -------- | -------- | ------------------- | | segments | number[] | An array of numbers that specify distances to alternately draw a line and a gap.| **Example** @@ -2137,7 +2344,7 @@ struct SetLineDash { } } ``` - ![zh-cn_image_000000127777772](figures/zh-cn_image_000000127777772.png) + ![en-us_image_000000127777772](figures/en-us_image_000000127777772.png) ### getLineDash @@ -2148,29 +2355,37 @@ Obtains the dash line style. **Return value** -| Type | Description | -| ----- | ------------------------ | +| Type | Description | +| -------- | ------------------------ | | number[] | An array describing the interval of alternate line segments and length of spacing.| **Example** ```ts // xxx.ets - @Entry - @Component - struct GetLineDash { +@Entry +@Component +struct OffscreenCanvasGetLineDash { + @State message: string = 'Hello World' private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + console.error('before getlinedash clicked') + let res = this.offContext.getLineDash() + console.error(JSON.stringify(res)) + }) Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) + .onReady(() => { this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.setLineDash([10,20]) this.offContext.stroke(); @@ -2180,53 +2395,14 @@ Obtains the dash line style. }) } .width('100%') - .height('100%') } + .height('100%') } +} ``` +![en-us_image_000000127777778](figures/en-us_image_000000127777778.png) -### transferFromImageBitmap - -transferFromImageBitmap(bitmap: ImageBitmap): void - -Displays the specified **ImageBitmap** object. - -**Parameters** - -| Parameters | Type | Description | -| ------ | ----------- | ------------------ | -| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct GetLineDash { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.fillRect(0, 0, 200, 200) - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') - } - } - ``` - ![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png) ### toDataURL @@ -2250,7 +2426,7 @@ Generates a URL containing image display information. **Example** ```ts - // xxx.ets +// xxx.ets @Entry @Component struct ToDataURL { @@ -2275,6 +2451,19 @@ struct ToDataURL { ``` +### imageSmoothingQuality + +imageSmoothingQuality(quality: imageSmoothingQuality) + +Sets the quality of image smoothing. This API is a void API. + + **Parameters** + +| Name | Type | Description | +| ------- | --------------------- | ---------------------------------------- | +| quality | imageSmoothingQuality | Quality of image smoothing. The value can be **'low'**, **'medium'**,or **'high'**.| + + ### transferToImageBitmap transferToImageBitmap(): ImageBitmap @@ -2285,7 +2474,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O | Type | Description | | ---------------------------------------- | --------------- | -| [ImageData](ts-components-canvas-imagebitmap.md)| Pixel data rendered on the **OffscreenCanvas**.| +| [ImageBitmap](ts-components-canvas-imagebitmap.md) | Pixel data rendered on the **OffscreenCanvas**.| **Example** @@ -2294,10 +2483,11 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O // xxx.ets @Entry @Component - struct CanvasExample { + struct PutImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2305,7 +2495,14 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.restore() + var imageData = this.offContext.createImageData(100, 100) + for (var i = 0; i < imageData.data.length; i += 4) { + imageData.data[i + 0] = 255 + imageData.data[i + 1] = 0 + imageData.data[i + 2] = 255 + imageData.data[i + 3] = 255 + } + this.offContext.putImageData(imageData, 10, 10) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2315,6 +2512,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O } } ``` +![en-us_image_0000001238952387](figures/en-us_image_0000001238952387.png) ### restore @@ -2326,29 +2524,35 @@ Restores the saved drawing context. ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.restore() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) } + .width('100%') + .height('100%') } +} ``` +![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### save @@ -2361,29 +2565,35 @@ Saves the current drawing context. ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.save() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) }) - } - .width('100%') - .height('100%') } + .width('100%') + .height('100%') } +} ``` +![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### createLinearGradient diff --git a/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md b/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md index c35cfd163fc86189bfb52182513ce2202d17e398..c393bf5812f9508448891111012d6c839cf6fb5c 100644 --- a/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md +++ b/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md @@ -17,7 +17,7 @@ Shared element transition can be used for transition between pages, for example, ## Example - The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image. +The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image. ```ts // xxx.ets diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md index f6a533065bdf4cb67d2dd683989b87c78af56eda..25737f363751988499f8bc93232b6d4733470b54 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -10,10 +10,10 @@ You can set the background of a component. | Name| Type| Description| | -------- | -------- | -------- | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | The table below describes the attributes used to set the background color of a component.| -| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. | +| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.
**src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. | | backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.
Default value: **ImageSize.Auto**| -| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.
Default value:
{
x: 0,
y: 0
} | +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.
Default value:
**{
x: 0,
y: 0
}** | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md index 7f9b88479d562dad8a2644f1bd4c1be9176e02b7..0b055bbfa0c84cf592d13c4fe26a04ab400b3a5a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md @@ -14,11 +14,11 @@ You can apply background blur effects to a component. ## BlurStyle - | Name | Description | - | ------- | ---------- | - | Thin | Thin material. | - | Regular | Regular material. | - | Thick | Thick material. | +| Name | Description | +| ------- | ---------- | +| Thin | Thin material. | +| Regular | Regular material. | +| Thick | Thick material. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md index cfc0e91df2dfb22513ec43800e6a9ed7fecc73e7..9b36249f0a6e49598b50d0e3e2333ab9c3882bc3 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md @@ -77,7 +77,7 @@ Sends a touch event. | Name | Type | Mandatory | Description | | ----- | ----------- | ---- | ------------------------------------------------------------ | -| event | TouchObject | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).| +| event | [TouchObject](ts-universal-events-touch.md#touchobject) | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).| **Return value** @@ -95,7 +95,7 @@ Sends a key event. | Name | Type | Mandatory | Description | | ----- | -------- | ---- | ------------------------------------------------------------ | -| event | KeyEvent | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).| +| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).| **Return value** @@ -113,7 +113,7 @@ Sends a mouse event. | Name | Type | Mandatory | Description | | ----- | ---------- | ---- | --------------------------------------- | -| event | MouseEvent | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).| +| event | [MouseEvent](ts-universal-mouse-key.md#mouseevent) | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).| **Return value** @@ -132,6 +132,7 @@ class Utils { static rect_bottom; static rect_value; + // Obtain the coordinates of the rectangular area occupied by the component. static getComponentRect(key) { let strJson = getInspectorByKey(key); let obj = JSON.parse(strJson); @@ -171,7 +172,7 @@ struct IdExample { console.info(getInspectorTree()) this.text = "Button 'click to start' is clicked" setTimeout(() => { - sendEventByKey("longClick", 11, "") + sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick". }, 2000) }).id('click') @@ -183,18 +184,18 @@ struct IdExample { console.info('long clicked') this.text = "Button 'longClick' is longclicked" setTimeout(() => { - let rect = Utils.getComponentRect('onTouch') + let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch". let touchPoint: TouchObject = { id: 1, - x: rect.left + (rect.right - rect.left) / 2, - y: rect.top + (rect.bottom - rect.top) / 2, + x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center. type: TouchType.Down, - screenX: rect.left + (rect.right - rect.left) / 2, - screenY: rect.left + (rect.right - rect.left) / 2, + screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate of the component center. } - sendTouchEvent(touchPoint) + sendTouchEvent(touchPoint) // Send a touch event. touchPoint.type = TouchType.Up - sendTouchEvent(touchPoint) + sendTouchEvent(touchPoint) // Send a touch event. }, 2000) })).id('longClick') @@ -205,14 +206,14 @@ struct IdExample { console.info('onTouch is clicked') this.text = "Button 'onTouch' is clicked" setTimeout(() => { - let rect = Utils.getComponentRect('onMouse') + let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse". let mouseEvent: MouseEvent = { button: MouseButton.Left, action: MouseAction.Press, - x: rect.left + (rect.right - rect.left) / 2, - y: rect.top + (rect.bottom - rect.top) / 2, - screenX: rect.left + (rect.right - rect.left) / 2, - screenY: rect.top + (rect.bottom - rect.top) / 2, + x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center. + screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + screenY: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center. timestamp: 1, target: { area: { @@ -230,7 +231,7 @@ struct IdExample { }, source: SourceType.Mouse } - sendMouseEvent(mouseEvent) + sendMouseEvent(mouseEvent) // Send a mouse event. }, 2000) }).id('onTouch') @@ -250,7 +251,7 @@ struct IdExample { metaKey: 0, timestamp: 0 } - sendKeyEvent(keyEvent) + sendKeyEvent(keyEvent) // Send a key event. }, 2000) }).id('onMouse') diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md index 874baf8801ad127b5bc494bb2601bce1fd7d917d..6e7645eabe12366ced89fb469334612d2205bd9f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md @@ -12,7 +12,7 @@ The **enabled** attribute sets whether a component responds to user interactions | Name | Type | Description | | ------- | ------- | ---------------------------------------- | -| enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions,
and **false** means the opposite.
Default value: **true**| +| enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions, and **false** means the opposite.
Default value: **true** | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md index cbcf94d324ce0f13098515e1932bc9f77cf6b404..da9f86c336021bc5f7cc10b57803ef7ef2371f2f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md @@ -23,7 +23,6 @@ @Entry @Component struct FlexExample { - build() { Column({ space: 5 }) { Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -31,11 +30,18 @@ struct FlexExample { // The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height(). Flex() { Text('flexBasis(100)') - .flexBasis('100').height(100).lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexBasis('100') + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) Text('flexBasis("auto")') - .flexBasis('auto').width('60%').height(100).lineHeight(70) - .backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .flexBasis('auto') + .width('60%') + .height(100) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -43,11 +49,17 @@ struct FlexExample { // flexGrow() specifies the percentage of the remaining space allocated to the component. Flex() { Text('flexGrow(2)') - .flexGrow(2).height(100).lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexGrow(2) + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) Text('flexGrow(1)') - .flexGrow(1).height(100).lineHeight(70) - .backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .flexGrow(1) + .height(100) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -55,13 +67,25 @@ struct FlexExample { // The ratio of text1 is 0, and the default values of other parameters are 1. If the components cannot be completely displayed, the last two components are shrunk proportionally. The first component is not shrunk. Flex({ direction: FlexDirection.Row }) { Text('flexShrink(0)') - .flexShrink(0).width('50%').height(100).lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexShrink(0) + .width('50%') + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) Text('no flexShrink') - .width('40%').height(100).lineHeight(70).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .width('40%') + .height(100) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) Text('flexShrink(2)') - .flexShrink(2).width('40%').height(100) .lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexShrink(2) + .width('40%') + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -70,8 +94,12 @@ struct FlexExample { Text('no alignSelf,height:80').width('33%').height(80) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) Text('alignSelf stretch') - .alignSelf(ItemAlign.Stretch).width('33%').height(80).lineHeight(70) - .backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .alignSelf(ItemAlign.Stretch) + .width('33%') + .height(80) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) Text('no alignSelf,height:100').width('34%').height(100) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index 9396d3f0fc3cf34b1eff351edbd3f1af19cf26da..c82ec4fab433b607cf344864a1126ac94332e89c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -17,8 +17,8 @@ None | Name | Type | Default Value| Description | | ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | -| blur | number | - | Blur effect of the current component' content. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred.| -| backdropBlur | number | - | Blur effect of the current component' background. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred.| +| blur | number | - | Adds the content blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred. | +| backdropBlur | number | - | Adds the background blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred. | | shadow | {
radius: number \| [Resource](ts-types.md#resource),
color?: Color \| string \| Resource,
offsetX?: number \| Resource,
offsetY?: number \| Resource
} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), x-axis offset (optional; 0 by default), and y-axis offset (optional; 0 by default). The offset unit is px.| | grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage.| | brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness.| @@ -78,4 +78,4 @@ struct ImageEffectsExample { } ``` -image-effect +![](figures/image-effect.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 69037d82bd8efc5e3028823381c6a8d9406fe329..3cab264048f797063baf0d40f5b489807033967a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -4,7 +4,7 @@ The location attribute sets the alignment mode, layout direction, and position o > **NOTE** > -> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Attributes @@ -15,8 +15,8 @@ The location attribute sets the alignment mode, layout direction, and position o | align | [Alignment](ts-appendix-enums.md#alignment) | Alignment of the component content. This attribute is valid only when the values of **width** and **height** are greater than the size of the component content.
Default value: **Alignment.Center**| | direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.
Default value: **Direction.Auto**| | position | [Position](ts-types.md#position8) | Offset of the component anchor point relative to the top start edge of the parent component. The offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| -| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.
Default value:
{
x: 0,
y: 1
} | -| offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 1
} | +| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.
Default value:
**{
x: 0,
y: 1**
} | +| offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
**{
x: 0,
y: 1
}** | | alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md index 6292412ddfe94444dd8756fef77b0c1df664eecf..db1e33a8ed8e723c626e81fc4bbb6cd9915948fe 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md @@ -12,7 +12,7 @@ You can set the opacity of a component. | Name | Type | Description | | ------- | ---------------------------------------- | ---------------------------------------- | -| opacity | number \| [Resource](ts-types.md#resource) | Opacity of a component. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.
Default value: **1**| +| opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout.
**NOTE**
A child component can inherit this attribute of its parent component. Default value: **1**| ## Example @@ -30,6 +30,10 @@ struct OpacityExample { Text().width('90%').height(50).opacity(0.7).backgroundColor(0xAFEEEE) Text('opacity(0.4)').fontSize(9).width('90%').fontColor(0xCCCCCC) Text().width('90%').height(50).opacity(0.4).backgroundColor(0xAFEEEE) + Text('opacity(0.1)').fontSize(9).width('90%').fontColor(0xCCCCCC) + Text().width('90%').height(50).opacity(0.1).backgroundColor(0xAFEEEE) + Text('opacity(0)').fontSize(9).width('90%').fontColor(0xCCCCCC) + Text().width('90%').height(50).opacity(0).backgroundColor(0xAFEEEE) } .width('100%') .padding({ top: 5 }) @@ -37,4 +41,4 @@ struct OpacityExample { } ``` -![en-us_image_0000001256858385](figures/en-us_image_0000001256858385.gif) +![opacity.png](figures/opacity.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index b24dfab3a25c47e323201e70b7261f4db2408015..9710a01a6870933d3b832ce589e192fe0cbcb87d 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -1,6 +1,6 @@ # Popup Control -The popup attribute defines the popup displayed when a component is clicked. +You can bind a popup to a component, specifying its content, interaction logic, and display status. > **NOTE** > @@ -12,7 +12,7 @@ The popup attribute defines the popup displayed when a component is clicked. | Name | Type | Description | | ---------- | ------------------------------------- | --------------------------------------- | -| bindPopup | show: boolean,
popup: PopupOptions \| CustomPopupOptions8+ | Settings of the popup bound to the component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the popup.| +| bindPopup | show: boolean,
popup: [PopupOptions](#popupoptions) \| [CustomPopupOptions](#custompopupoptions8)8+ | Binds a popup to the component.
**show**: whether to show the popup. The default value is **false**, indicating that the popup is hidden.
**popup**: parameters of the popup.| ## PopupOptions @@ -21,6 +21,7 @@ The popup attribute defines the popup displayed when a component is clicked. | message | string | Yes | Content of the popup message. | | placementOnTop | boolean | No | Whether to display the popup above the component. The default value is **false**. | | arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. | +| showInSubWindow9+ | boolean | No | Whether to show the popup in the subwindow. The default value is **false**.| | primaryButton | {
value: string,
action: () => void
} | No | Primary button.
**value**: text of the primary button in the popup.
**action**: callback for clicking the primary button.| | secondaryButton | {
value: string,
action: () => void
} | No | Secondary button.
**value**: text of the secondary button in the popup.
**action**: callback for clicking the secondary button.| | onStateChange | (event: { isVisible: boolean }) => void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible. | @@ -29,9 +30,10 @@ The popup attribute defines the popup displayed when a component is clicked. | Name | Type | Mandatory | Description | | -------------------------| ------------------------- | ---- | ---------------------------------------------------- | -| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Builder of the popup content. | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. | | placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.
Default value: **Placement.Bottom** | | arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. | +| showInSubWindow9+ | boolean | No | Whether to show the popup in the subwindow. The default value is **false**.| | maskColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup mask. | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. | | enableArrow | boolean | No | Whether to display an arrow.
Since API version 9, if the location set for the popup arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.
Default value: **true**| @@ -40,81 +42,80 @@ The popup attribute defines the popup displayed when a component is clicked. ## Example - ```ts // xxx.ets @Entry @Component struct PopupExample { - @State noHandlePopup: boolean = false @State handlePopup: boolean = false @State customPopup: boolean = false + // Popup builder @Builder popupBuilder() { Row({ space: 2 }) { - Image('/resource/ic_public_thumbsup.svg').width(24).height(24).margin({ left: -5 }) + Image($r("app.media.image")).width(24).height(24).margin({ left: -5 }) Text('Custom Popup').fontSize(10) - }.width(100).height(50).backgroundColor(Color.White) + }.width(100).height(50).padding(5) } build() { Flex({ direction: FlexDirection.Column }) { - Button('no handle popup') - .onClick(() => { - this.noHandlePopup = !this.noHandlePopup - }) - .bindPopup(this.noHandlePopup, { - message: 'content1 content1', - placementOnTop: false, - onStateChange: (e) => { - console.info(e.isVisible.toString()) - if (!e.isVisible) { - this.noHandlePopup = false - } - } - }) - .position({ x: 100, y: 50 }) - - Button('with handle popup') + // PopupOptions for setting the popup + Button('PopupOptions') .onClick(() => { this.handlePopup = !this.handlePopup }) .bindPopup(this.handlePopup, { - message: 'content2 content2', + message: 'This is a popup with PopupOptions', placementOnTop: true, + showInSubWindow:false, primaryButton: { - value: 'ok', + value: 'confirm', action: () => { this.handlePopup = !this.handlePopup - console.info('secondaryButton click') + console.info('confirm Button click') + } + }, + // Secondary button + secondaryButton: { + value: 'cancel', + action: () => { + this.handlePopup = !this.handlePopup; + console.info('cancel Button click') } }, onStateChange: (e) => { console.info(e.isVisible.toString()) + if (!e.isVisible) { + this.handlePopup = false + } } }) - .position({ x: 100, y: 200 }) + .position({ x: 100, y: 50 }) + - Button('custom popup') + // CustomPopupOptions for setting the popup + Button('CustomPopupOptions') .onClick(() => { this.customPopup = !this.customPopup }) .bindPopup(this.customPopup, { builder: this.popupBuilder, - placement: Placement.Bottom, + placement: Placement.Top, maskColor: 0x33000000, - popupColor: Color.White, + popupColor: Color.Yellow, enableArrow: true, + showInSubWindow: false, onStateChange: (e) => { if (!e.isVisible) { this.customPopup = false } } }) - .position({ x: 100, y: 350 }) + .position({ x: 80, y: 200 }) }.width('100%').padding({ top: 5 }) } } ``` -![en-us_image_0000001212058458](figures/en-us_image_0000001212058458.gif) +![figures/popup.gif](figures/popup.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index 446cc542dcd6d1e9110c3975e8b1d16fe5ceeb02..f7937b97bffbb5ab4f596940910a22e9922b4040 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -16,7 +16,7 @@ The text style attributes are used to set the style for text in a component. | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Font color. | | fontSize | Length \| [Resource](ts-types.md#resource) | Font size. If the value is of the number type, the unit fp is used. | | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.
Default value: **FontStyle.Normal** | -| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, 400, "bold", "bolder", "lighter", "regular", and "medium", which correspond to the enumerated values in FontWeight.
Default value: **FontWeight.Normal** | +| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal** | | fontFamily | string \| [Resource](ts-types.md#resource) | Font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md index 982ea614f7560050b2993cccacb67a841cbf26bd..2c8ba7c33a29b398ae2144c6435fe0d6a10671a6 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md @@ -11,7 +11,7 @@ The area change event is triggered when the component's size, position, or any o | Name | Bubbling Supported| Description | | ---------------------------------------- | ---- | ---------------------------------------- | -| onAreaChange(event: (oldValue: Area, newValue: Area) => void) | No | Triggered when the component area changes. For details about the **Area** type, see [Area](ts-types.md#area8).| +| onAreaChange(event: (oldValue: [Area](ts-types.md#area8), newValue: [Area](ts-types.md#area8)) => void) | No | Triggered when the component area changes.| ## Example @@ -22,7 +22,7 @@ The area change event is triggered when the component's size, position, or any o @Component struct AreaExample { @State value: string = 'Text' - @State size1: string = '' + @State sizeValue: string = '' build() { Column() { @@ -33,9 +33,9 @@ struct AreaExample { }) .onAreaChange((oldValue: Area, newValue: Area) => { console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`) - this.size1 = JSON.stringify(newValue) + this.sizeValue = JSON.stringify(newValue) }) - Text('new area is: \n' + this.size).margin({ right: 30, left: 30 }) + Text('new area is: \n' + this.sizeValue).margin({ right: 30, left: 30 }) } .width('100%').height('100%').margin({ top: 30 }) } diff --git a/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md b/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md index df4ee9686b18f08139ef6aa814fdda50eea2a015..1d34a1ae15448105d23e77989c031daf50ace78e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md @@ -1,6 +1,6 @@ # Visible Area Change Event -The visible area change event of a component refers to the change in the visual portion of a component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing. +The visible area change event of a component refers to the change in the visual portion of the component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing. > **NOTE** > @@ -23,8 +23,8 @@ The visible area change event of a component refers to the change in the visual struct ScrollExample { scroller: Scroller = new Scroller() private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - @State testTextStr: string = "test" - @State testRowStr: string = "test" + @State testTextStr: string = 'test' + @State testRowStr: string = 'test' build() { Column() { @@ -46,22 +46,22 @@ struct ScrollExample { .height(200) .margin({ top: 50, bottom: 20 }) .backgroundColor(Color.Green) - // Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen. + // Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen. .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { - console.info("Test Text isVisible: " + isVisible + ", currentRatio:" + currentRatio) + console.info('Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio) if (isVisible && currentRatio >= 1.0) { - console.info("Test Text is fully visible. currentRatio:" + currentRatio) - this.testTextStr = "Test Text is fully visible" + console.info('Test Text is fully visible. currentRatio:' + currentRatio) + this.testTextStr = 'Test Text is fully visible' } if (!isVisible && currentRatio <= 0.0) { - console.info("Test Text is completely invisible.") - this.testTextStr = "Test Text is completely invisible" + console.info('Test Text is completely invisible.') + this.testTextStr = 'Test Text is completely invisible' } }) Row() { - Text("Test Row Visible Change") + Text('Test Row Visible Change') .fontSize(20) .margin({ bottom: 20 }) @@ -69,15 +69,15 @@ struct ScrollExample { .height(200) .backgroundColor(Color.Yellow) .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { - console.info("Test Row isVisible:" + isVisible + ", currentRatio:" + currentRatio) + console.info('Test Row isVisible:' + isVisible + ', currentRatio:' + currentRatio) if (isVisible && currentRatio >= 1.0) { - console.info("Test Row is fully visible.") - this.testRowStr = "Test Row is fully visible" + console.info('Test Row is fully visible.') + this.testRowStr = 'Test Row is fully visible' } if (!isVisible && currentRatio <= 0.0) { - console.info("Test Row is is completely invisible.") - this.testRowStr = "Test Row is is completely invisible" + console.info('Test Row is is completely invisible.') + this.testRowStr = 'Test Row is is completely invisible' } }) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md index 31a0c9f822ba7485c1df1982a9e5dc35b210a823..226a6b6030f7050ddff13e6ccc37ddd3663afc4e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md @@ -11,7 +11,7 @@ A click event is triggered when a component is clicked. | Name | Bubbling Supported| Description | | ---------------------------------------- | ---- | --------------------------------- | -| onClick(event: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about the event parameters, see **ClickEvent**.| +| onClick(event: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about **event**, see **ClickEvent**.| ## ClickEvent | Name | Type | Description | @@ -20,8 +20,9 @@ A click event is triggered when a component is clicked. | screenY | number | Y coordinate of the click relative to the upper left corner of the application window. | | x | number | X coordinate of the click relative to the upper left corner of the component being clicked. | | y | number | Y coordinate of the click relative to the upper left corner of the component being clicked. | -| target8+ | [EventTarget](#eventtarget8) | Target element that is clicked. | -| timestamp | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| +| timestamp8+ | number | Timestamp of the event. It is the interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| +| target8+ | [EventTarget](#eventtarget8) | Display area of the object that triggers the event.| +| source8+ | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.| ## EventTarget8+ @@ -42,15 +43,25 @@ struct ClickExample { build() { Column() { - Button('Click').backgroundColor(0x2788D9).width(100).height(40) - .onClick((event: ClickEvent) => { - console.info(this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY - + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:(' - + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:' - + event.target.area.width + '\n height:' + event.target.area.height) - }) - Text(this.text).padding(15) - }.height(350).width('100%').padding(10) + Row({ space: 20 }) { + Button('Click').width(100).height(40) + .onClick((event: ClickEvent) => { + this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY + + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:(' + + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:' + + event.target.area.width + '\n height:' + event.target.area.height + '\ntimestamp' + event.timestamp; + }) + Button('Click').width(200).height(50) + .onClick((event: ClickEvent) => { + this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY + + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:(' + + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:' + + event.target.area.width + '\n height:' + event.target.area.height + '\ntimestamp' + event.timestamp; + }) + }.margin(20) + + Text(this.text).margin(15) + }.width('100%') } } ``` diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index c777a2a3dbf580505a97ff0fabd3908423d8e004..02d3179909afd790d353e4f02eefba814bff35c4 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -27,9 +27,9 @@ A drag event is triggered when a component is dragged. ## extraParam - Provides additional information required for dragging an item. +Provides additional information required for dragging an item. - **extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**. +**extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**. | Name | Type | Description | | ------------- | ------ | ---------------------------------------- | @@ -38,7 +38,7 @@ A drag event is triggered when a component is dragged. ## DragEvent -| Sample Code | Return Value Type | Description | +| Name | Return Value Type | Description | | ------ | ------ | ---------------- | | getX() | number | X-coordinate of the item that is being dragged, in vp.| | getY() | number | Y-coordinate of the item that is being dragged, in vp.| diff --git a/en/application-dev/reference/errorcodes/errorcode-device-manager.md b/en/application-dev/reference/errorcodes/errorcode-device-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..3e0459cebcb89d3d501bc331f9526320cd7d72e6 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-device-manager.md @@ -0,0 +1,71 @@ +# Device Management Error Codes + +## 11600101 Service Invoking Exception + +**Error Message** + +Failed to execute the function. + +**Possible Causes** + +An error occurred during internal invocation. + +**Procedure** + +Call the API again. + +## 11600102 Failed to Obtain the Service + +**Error Message** + +Failed to obtain the service. + +**Possible Causes** + +The service is not started or fails to start. + +**Procedure** + +Check whether the service is started normally and obtain the service again. + +## 11600103 Authentication Unavailable + +**Error Message** + +Authentication invalid. + +**Possible Causes** + +The last authentication service is still in progress. + +**Procedure** + +Wait until the last authentication service is complete and call the authentication API again. + +## 11600104 Discovery Unavailable + +**Error Message** + +Discovery invalid. + +**Possible Causes** + +The last discovery service is still in progress. + +**Procedure** + +Wait until the last discovery service is complete and call the discovery API again. + +## 11600105 Publish Unavailable + +**Error Message** + +Publish invalid. + +**Possible Causes** + +The last publish service is still in progress. + +**Procedure** + +Wait until the last publish service is complete and call the publish API again. diff --git a/en/application-dev/reference/errorcodes/errorcode-huks.md b/en/application-dev/reference/errorcodes/errorcode-huks.md new file mode 100644 index 0000000000000000000000000000000000000000..7bab2f0be7353cefecbe458b6435aaaf213429d4 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-huks.md @@ -0,0 +1,228 @@ +# HUKS Error Codes + +## 12000001 Feature Not Supported + +**Error Message** + +`${messageInfo}` is not supported. + +**Possible Causes** + +The API is supported, but certain features in the API, such as the algorithm, are not supported. + +**Procedure** + +Modify the parameters and use the features supported. + +## 12000002 Missing Key Algorithm Parameter +**Error Message** + +Failed to obtain `${messageInfo}`. It is not set in ParamSet. + +**Possible Causes** + +The key parameter is not set. + +**Procedure** + +1. Determine the missing parameter from the error message. +2. Set the parameter. + +## 12000003 Invalid Key Algorithm Parameter + +**Error Message** + +Invalid `${messageInfo}`. + +**Possible Causes** + +An invalid parameter is found. + +**Procedure** + +1. Determine the invalid parameter from the error message. +2. Correct the invalid parameter. + +## 12000004 File Error + +**Error Message** + +Failed to read the file. + +Failed to write the file. + +**Possible Causes** + +The file operation failed. + +**Procedure** + +1. Check whether the disk space is used up and whether the file system is abnormal. +2. Clear the disk space. + +## 12000005 IPC Error + +**Error Message** + +IPC timed out. + +Failed to obtain messages from IPC. + +**Possible Causes** + +IPC failed. + +**Procedure** + +Locate and rectify the IPC failure. + +## 12000006 Algorithm Library Operation Failed + +**Error Message** + +Crypto engine error. + +**Possible Causes** + +The algorithm library operation fails. The possible causes include the following: + +1. The encryption and decryption on the algorithm library failed due to incorrect ciphertext data. +2. Incorrect key parameters exist. + +**Procedure** + +1. Check and correct the ciphertext data. +2. Check and correct the key parameters. + +## 12000007 Failed to Access the Key Due to Invalidated Credential + +**Error Message** + +This credential is invalidated permanently. + +**Possible Causes** + +The possible causes include the following: + +1. The key is configured with the user access control attribute and becomes invalid after the password is cleared. +2. The key is configured with the user access control attribute and becomes invalid after a new biometric feature is enrolled. + +**Procedure** + +1. Locate the cause of the authentication failure based on the log. +2. If the authentication fails due to the access control attribute configured, the key cannot be used any more. + +## 12000008 Failed to Access the Key Due to a Failure in Authentication Token Verification + +**Error Message** + +The authentication token verification failed. + +**Possible Causes** + +The authentication token verification failed due to an incorrect challenge value. + +**Procedure** + +1. Check whether the challenge for userIAM authentication is correctly assembled. +2. If the challenge value is incorrect, modify the assembly mode, use the bytes generated by HUKS to assembly challenge value, and pass it to userIAM for authentication. + +## 12000009 Key Access Timed Out + +**Error Message** + +The Authentication token timed out. + +**Possible Causes** + +The authentication failed because the authentication token timed out. + +**Procedure** + +The difference between the current time and the authentication token generation time must be less than the timeout interval. Otherwise, the access will be rejected. + +## 12000010 Key Operation Sessions Reaches the Limit + +**Error Message** + +The number of key operation sessions has reached the limit. + +**Possible Causes** + +The number of concurrent key operation sessions has reached the maximum (15). + +**Procedure** + +1. Check whether there are multiple key session operations (**init** operations) for the same application. If yes, modify the code to avoid concurrent invoking. +2. If the key operation sessions are set up for different applications, wait until the sessions are released. + +## 12000011 The Entity Does Not Exist + +**Error Message** + +The entity does not exist. + +**Possible Causes** + +The key corresponding to the key alias does not exist. + +**Procedure** + +1. Check whether the key alias is misspelled. +2. Check whether the key corresponding to the key alias is successfully generated. + +## 12000012 External Error + +**Error Message** + +External error `${messageInfo}`. + +**Possible Causes** + +An external error, such as a hardware fault or file error occurs. + +**Procedure** + +Provide the error code and log information to the related party. + +## 12000013 The Credential Does Not Exist + +**Error Message** + +The credential does not exist. + +**Possible Causes** + +The credential, such as the PIN, fingerprint, or face image, is not enrolled. + +**Procedure** + +Enroll the credential or change the authentication type bound to the key. + +## 12000014 Insufficient Memory + +**Error Message** + +Memory is insufficient. + +**Possible Causes** + +The system memory is insufficient. + +**Procedure** + +Release memory or restart the device. + +## 12000015 Failed to Invoke Other System Services + +**Error Message** + +Failed to call the `${messageInfo}` service to do `${messageInfo}`. + +**Possible Causes** + +The called system service has not started. + +**Procedure** + +Wait for the system service to start and call the API again. diff --git a/en/application-dev/reference/errorcodes/errorcode-sensor.md b/en/application-dev/reference/errorcodes/errorcode-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..571156ec00328b0ba564cd6174e6fb81aa5154b1 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-sensor.md @@ -0,0 +1,20 @@ +# Sensor Error Codes + +## 14500101 Service exception. + +**Error Message** + +Service exception. + +**Description** + +This error code is reported if the HDI service is abnormal when the **on**, **once**, or **off** interface of the sensor module is called. + +**Possible Causes** + +The HDI service is abnormal. + +**Procedure** + +1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval. +2. If the operation fails for three consecutive times, stop the retry. You can also attempt to obtain the sensor list to check for device availability. diff --git a/en/application-dev/reference/errorcodes/errorcode-vibrator.md b/en/application-dev/reference/errorcodes/errorcode-vibrator.md new file mode 100644 index 0000000000000000000000000000000000000000..f5dc329c1e96d945f76c7625b365a53fe50477b4 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-vibrator.md @@ -0,0 +1,21 @@ +# Vibrator Error Codes + +## 14600101 Device operation failed. + +**Error Message** + +Device operation failed. + +**Description** + +This error code is reported if the HDI service is abnormal or the device is occupied when the **startVibration** interface of the vibrator module is called. + +**Possible Causes** + +1. The HDI service is abnormal. +2. The device is occupied. + +**Procedure** + +1. Retry the operation at a specified interval or at an exponential increase interval. If the operation fails for three consecutive times, stop the retry. You can also obtain the vibrator list to check for device availability. +2. Set a higher priority for the vibrator. diff --git a/en/application-dev/reference/syscap-list.md b/en/application-dev/reference/syscap-list.md new file mode 100644 index 0000000000000000000000000000000000000000..51ada8f2b45879986ed8aa932336827cb5b546f1 --- /dev/null +++ b/en/application-dev/reference/syscap-list.md @@ -0,0 +1,1396 @@ +# SysCap List + +SysCap, short for System Capability, refers to a standalone feature in the operating system. + +Before using an API for development, you are advised to familiarize yourself with [SysCap](../quick-start/syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type. + +## SystemCapability.ArkUI.ArkUI.Full + +ArKUI standard system + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ArkUI.ArkUI.Lite + +ArkUI small system + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.ArkUI.ArkUI.Napi + +NAPI functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ArkUI.ArkUI.Libuv + +libuv functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ArkUI.UiAppearance + +Appearance configuration + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework + +Bundle manager service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.DistributedBundleFramework + +Distributed scheduler + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleTool + +Bundle manager CLI tool + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.Zlib + +zlib compression and decompression tool + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.PackingTool + +Packing and unpacking tools for bundle management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.Graphic.Graphic2D.WebGL + +WebGL 1.0 API + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Graphic.Graphic2D.WebGL2 + +WebGL 2.0 API + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | No | No | No | No | No | + +## SystemCapability.WindowManager.WindowManager.Core + +Window manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.WindowManager.WindowManager.MutiScreen + +Multi-screen capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.CommonEvent + +Common event + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.Notification + +Notification + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.ReminderAgent + +reminderAgent + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.Emitter + +Event emitter service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.IPC.Core + +Inter-process communication (IPC) + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.Communication.SoftBus.Core + +DSoftBus + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Communication.NetManager.Core + +Basic network management services + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NetManager.Extension + +Extended network management services + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NetStack + +Basic network stack capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.Core + +Basic Wi-Fi capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.STA + +Wi-Fi STA capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.AP.Core + +Wi-Fi AP capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.AP.Extension + +Wi-Fi AP extension capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | Yes | + +## SystemCapability.Communication.WiFi.P2P + +Wi-Fi P2P capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.Bluetooth.Core + +Bluetooth service and protocol stack + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.Bluetooth.Lite + +Bluetooth lightweight service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NFC.Core + +NFC + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.Communication.ConnectedTag + +Active NFC tag service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.Location.Location.Core + +Basic capabilities of the location service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Geocoder + +Geocoding capability +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Geofence + +Geofencing capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Gnss + +GNSS hardware capabilities + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Lite + +Lite device capabilities of the location service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | No | No | No | + +## SystemCapability.MultimodalInput.Input.Core + +Basic input capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputDevice + +Input device management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.RemoteInputDevice + +Distributed input device management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputMonitor + +Input event listener + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputConsumer + +Input event consumer + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputSimulator + +Input event simulator + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputFilter + +Input event filter + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.PowerManager.BatteryManager.Extension + +Battery manager extension capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.PowerManager.BatteryStatistics + +Power consumption statistics + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.PowerManager.DisplayPowerManager + +Power management display + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.PowerManager.ThermalManager + +Temperature control + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.PowerManager.PowerManager.Core + +Core capabilities of the system power management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.PowerManager.PowerManager.Lite + +Lite device capabilities of the system power management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.PowerManager.BatteryManager.Core + +Core capabilities of the battery service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.PowerManager.BatteryManager.Lite + +Lite device capabilities of the battery service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.PowerManager.PowerManager.Extension + +Extension capabilities of the system power management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Multimedia.Media.Core + +Basic media capabilities + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioPlayer + +Media audio player capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioRecorder + +Media audio recorder capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoPlayer + +Media video player capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoRecorder + +Media video recorder capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.CodecBase + +Basic media codec capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioDecoder + +Media audio decoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioEncoder + +Media audio encoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoDecoder + +Media video decoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoEncoder + +Media video encoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.Spliter + +Media splitter capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.Muxer + +Media muxer capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.AVSession.Core + +Basic media session capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.AVSession.Manager + +Media session management capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Core + +Basic audio capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Renderer + +Audio output capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Capturer + +Audio input capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Device + +Audio device management capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Volume + +Audio volume management capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Communication + +Audio communication capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Camera.Core + +Basic camera capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Camera.DistributedCore + +Distributed camera capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.Core + +Basic image capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.ImageSource + +Image source decoding and parsing capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.ImagePacker + +Image packaging capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.ImageReceiver + +Image receiving capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.MediaLibrary.Core + +Basic capabilities of the media library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.MediaLibrary.SmartAlbum + +Smart album capability of the media library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.MediaLibrary.DistributedCore + +Distributed capability of the media library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Telephony.CoreService + +Basic cellular service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.CallManager + +Call management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Telephony.CellularCall + +Cellular call service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.CellularData + +Cellular data service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.SmsMms + +SMS and MMS services + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.StateRegistry + +Cellular network status registration service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Global.I18n + +Internationalization + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Global.ResourceManager + +Resource management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Customization.ConfigPolicy + +Customization framework + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Customization.EnterpriseDeviceManager + +Enterprise device management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Core + +Accessibility capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Vision + +Visual accessibility capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Hearing + +Audio accessibility capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Interaction + +Interaction assistance capability in accessibility + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | Yes | No | No | + +## SystemCapability.ResourceSchedule.WorkScheduler + +Work Scheduler + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + +Continuous task management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + +Transient task management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.UsageStatistics.App + +Application usage statistics + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +Application activity group + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Utils.Lang + +TS/JS language base library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiLog + +HiLog functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiLogLite + +Lite HiLog functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.HiviewDFX.HiTrace + +HiTrace for distributed tracing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.Hiview.FaultLogger + +FaultLogger for event recording + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiviewLite + +Lightweight Hiview service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.HiviewDFX.HiChecker + +HiChecker mode + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiCollie + +HiCollie for suspension fault detection + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiDumper + +HiDumper for system information exporting + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiAppEvent + +HiAppEvent for application event logging + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiSysEvent + +HiAppEvent for system event logging + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiEventLite + +HiEventLite for lightweight event logging + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | No | Yes | + +## SystemCapability.HiviewDFX.HiProfiler.HiDebug + +Debugging and tuning + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Update.UpdateService + +Update + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.DistributedHardware.DeviceManager + +Distributed Device Management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.DeviceAuth + +Mutual authentication between devices + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.DataTransitManager + +Library of data transmission management and control policies + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.DeviceSecurityLevel + +Device security level management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.Huks + +Hardware Unique Key (HUK) management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.AccessToken + +Access control + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Security.Cipher + +Encryption and decryption + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | Yes | No | + +## SystemCapability.Account.OsAccount + +Account + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Account.AppAccount + +Application account + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.UserIAM.UserAuth.Core + +Unified user authentication + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.UserIAM.UserAuth.PinAuth + +PIN authentication + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.UserIAM.UserAuth.FaceAuth + +Facial authentication + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.MiscServices.InputMethodFramework + +Input method framework + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Pasteboard + +Pasteboard service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Time + +Time, time zone, and timing service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.MiscServices.Wallpaper + +Wallpaper framework + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.ScreenLock + +Screen lock service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Upload + +Upload service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Download + +Download service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.FileManagement.StorageService.Backup + +Backup and restoration + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.StorageService.SpatialStatistics + +Spatial statistics + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.StorageService.Volume + +Volume management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.StorageService.Encryption + +File encryption capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.File.FileIO + +Basic file I/O interfaces + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.FileManagement.File.Environment + +Environment-related interfaces + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.FileManagement.File.DistributedFile + +Distributed file extension interfaces + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.AppFileService + +Application file sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.UserFileService + +User file access service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.USB.USBManager + +USB service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Sensors.Sensor + +Sensor service subscription + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Sensors.MiscDevice + +Miscellaneous devices- sensors + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Startup.SystemInfo + +Basic system information + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.DistributedDataManager.RelationalStore.Core + +Basic relational database capabilities + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.RelationalStore.Synchronize + +Distributed capability of relational databases + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.RelationalStore.Lite + +Lightweight relational database + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.DistributedDataManager.KVStore.Core + +Core capabilities of key-value databases + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.KVStore.Lite + +Core capabilities of lightweight key-value databases + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +Distributed key-value database + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataObject.DistributedObject + +Distributed data object + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.Preferences.Core + +Core capabilities of preferences data storage + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataShare.Core + +Basic capabilities of cross-process data sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataShare.Consumer + +Data conumser of cross-process data sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataShare.Provider + +Data provider of cross-process data sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityBase + +Definition of basic component running data, including wants and system configuration + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.Core + +Core basic functional modules for component runtime, including application initialization and GUI-less component running + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.FAModel + +Feature ability (FA) model + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.AbilityCore + +Universal components (with GUIs) + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.Mission + +Task management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityTools.AbilityAssistant + +CLI tool + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.Form + +Widget management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.DistributedAbilityManager + +continuationManager for starting the device selection module and updating the continuation status. + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Applications.ContactsData + +Contacts database + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Applications.Contacts + +Contacts + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Applictaions.settings.Core + +API setting + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Test.UiTest + +UiTest capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | No | No | No | + +## SystemCapability.Web.Webview.Core + +Webview component + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Cloud.AAID + +AAID management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Cloud.OAID + +OAID management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Cloud.VAID + +VAID management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | diff --git a/en/application-dev/security/huks-overview.md b/en/application-dev/security/huks-overview.md index cd918d5d3e24b7ac4e94e051f21fc495a44caa6d..b9b0b7a8530e41b40d1ed8d8c1eacb5ab451a7ad 100644 --- a/en/application-dev/security/huks-overview.md +++ b/en/application-dev/security/huks-overview.md @@ -12,17 +12,16 @@ OpenHarmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for ap ## Working Principles -HUKS manages keys through the following operations: +HUKS manages keys through the following APIs in an Init-Update-Finish model: -- **Init**: reads the key, creates a session ID, and returns the session ID to the caller. +- **InitSession**: reads the key, creates a session ID, and returns the session ID to the caller. -- **Update**: updates data by segment based on the session ID obtained by the **Init** operation. +- **UpdateSession**: updates data by segment based on the session ID obtained by **InitSession()**. -- **Finish**: processes all data transferred to HUKS and then releases resources. +- **FinishSession**: processes all the data transferred to HUKS and then releases resources. > **NOTICE**
-> The **Abort** operation must be invoked to terminate the use of the key when an error occurs in the **Init**, **Update**, or **Finish** operation. - +> **AbortSession()** must be called to terminate the use of the key when an error occurs in any of **InitSession()**, **UpdateSession()**, and **FinishSession()**. ## Constraints N/A diff --git a/en/application-dev/task-management/background-task-dev-guide.md b/en/application-dev/task-management/background-task-dev-guide.md index 6b01a096d29d9e6c96b2172f9fddadb7a7bb1801..a83f7f3092e207293011dd579ff08aa9c3192ddc 100644 --- a/en/application-dev/task-management/background-task-dev-guide.md +++ b/en/application-dev/task-management/background-task-dev-guide.md @@ -2,7 +2,13 @@ ## When to Use -If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. +If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension. The application can also request efficiency resources in the following scenarios for more flexibility: + +- The application should not be suspended within a period of time until it finishes the task. + +- The application requires system resources even when it is suspended. For example, an alarm clock requires timer resources even when being suspended. + +- The application needs to execute the task at an unlimited frequency and within a longer time. ## Transient Tasks @@ -12,7 +18,7 @@ If a service needs to be continued when the application or service module is run | API | Description | | ---------------------------------------- | ---------------------------------------- | -| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.
The default duration value of delayed suspension is 180000 when the battery level is normal and 60000 when the battery level is low.| +| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo)| Requests delayed suspension after the application switches to the background.
The default duration value of delayed suspension is 180000 when the battery level is normal and 60000 when the battery level is low.| | getRemainingDelayTime(requestId: number): Promise<number> | Obtains the remaining duration before the application is suspended.
This API uses a promise to return the result. | | cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. | @@ -485,3 +491,90 @@ export default class BgTaskAbility extends Ability { } }; ``` + +## Efficiency Resources + +### Available APIs + +**Table 4** Main APIs for efficiency resources + +| API | Description | +| ---------------------------------------- | ---------------------------------------- | +| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | Requests efficiency resources.| +| resetAllEfficiencyResources():void | Releases efficiency resources. | + + +### How to Develop + + +1. Request efficiency resources. + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +let request = { + resourceTypes: backgroundTaskManager.ResourceType.CPU, + isApply: true, + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: true, +}; +let res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); +``` + +2. Release some efficiency resources. + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +let request = { + resourceTypes: backgroundTaskManager.ResourceType.CPU, + isApply: false, + timeOut: 0, + reason: "reset", +}; +let res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); +``` + +3. Release all efficiency resources. + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); +``` + +### Development Examples + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +// Apply for efficiency resources. +let request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | + backgroundTaskManager.ResourceType.TIMER, + isApply: true, + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: true, +}; +let res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); + +// Release some efficiency resources. +request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, + isApply: false, + timeOut: 0, + reason: "reset", +}; +res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); + +// Release all efficiency resources. +backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); +``` diff --git a/en/application-dev/task-management/background-task-overview.md b/en/application-dev/task-management/background-task-overview.md index b3c21576f276b79c359e89d357890f7ddc26f438..a0b225b8d09761006267b52941455d1eb58a7497 100644 --- a/en/application-dev/task-management/background-task-overview.md +++ b/en/application-dev/task-management/background-task-overview.md @@ -9,10 +9,12 @@ Background tasks described in this document refer to the services that need to b - **No background task**: An application or service module does not need further processing when switched to the background. -- **Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension. +- **Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task to delay the suspension. - **Continuous task**: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP. +- **Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including CPU, WORK_SCHEDULER, software, and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended. + ## Transient Tasks @@ -61,3 +63,25 @@ OpenHarmony provides 9 background modes for services that require continuous tas - Ensure that the requested continuous task background mode matches the application type. If the background mode does not match the application type, the system will suspend the task once it detects the issue. - If a requested continuous task is not actually executed, the system will suspend the task once it detects the issue. - Each ability can request only one continuous task at a time. + +## Efficiency Resources +Efficiency resources are classified into CPU, WORK_SCHEDULER, software, and hardware resources. +An application or process is assigned the privileges associated with the obtained efficiency resources. For example, with the CPU resources, the application or process will not be suspended. With the WORK_SCHEDULER resources, the application or process has more time to execute a task and is not restricted by the execution frequency. With the software and hardware resources, related resources are not proxied when the application or process is suspended. + + +**Table 2** Efficiency resource types + +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| CPU | 1 | CPU resources, which prevent the application from being suspended. | +| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. | +| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. | +| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | +| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | +| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | +| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| + +### Restrictions on Using Efficiency Resources +- Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application. +- If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released. +- The WORK_SCHEDULER resources can be requested and released by applications, but not by processes. diff --git a/en/application-dev/ui/Readme-EN.md b/en/application-dev/ui/Readme-EN.md index 20d4a865e9ed33c9b7413adb2498d4826518ccb0..e4838da489a5d5bb3ac3651885c9d456ed7322eb 100644 --- a/en/application-dev/ui/Readme-EN.md +++ b/en/application-dev/ui/Readme-EN.md @@ -1,66 +1,26 @@ # UI Development - [ArkUI Overview](arkui-overview.md) -- TypeScript-based Declarative Development Paradigm +- UI Development with eTS-based Declarative Development Paradigm - [Overview](ui-ts-overview.md) - Framework Overview - File Organization - [Directory Structure](ts-framework-directory.md) - [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md) - - ["js" Tag](ts-framework-js-tag.md) - Resource Management - [Resource File Categories](ui-ts-basic-resource-file-categories.md) - - [Accessing Resources](ts-resource-access.md) + - [Resource Access](ts-resource-access.md) - [Pixel Units](ts-pixel-units.md) - - Declarative Syntax - - [Overview](ts-syntax-intro.md) - - General UI Description Specifications - - [Basic Concepts](ts-general-ui-concepts.md) - - Declarative UI Description Specifications - - [Configuration Without Parameters](ts-parameterless-configuration.md) - - [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md) - - - [Attribute Configuration](ts-attribution-configuration.md) - - [Event Configuration](ts-event-configuration.md) - - [Child Component Configuration](ts-child-component-configuration.md) - - Componentization - - [@Component](ts-component-based-component.md) - - [@Entry](ts-component-based-entry.md) - - [@Preview](ts-component-based-preview.md) - - [@Builder](ts-component-based-builder.md) - - [@Extend](ts-component-based-extend.md) - - [@CustomDialog](ts-component-based-customdialog.md) - - [@Styles](ts-component-based-styles.md) - - About UI State Management - - [Basic Concepts](ts-ui-state-mgmt-concepts.md) - - Managing Component States - - [@State](ts-component-states-state.md) - - [@Prop](ts-component-states-prop.md) - - [@Link](ts-component-states-link.md) - - Managing Application States - - [AppStorage](ts-application-states-appstorage.md) - - [LocalStorage](ui-ts-local-storage.md) - - [PersistentStorage](ts-application-states-apis-persistentstorage.md) - - [Environment](ts-application-states-apis-environment.md) - - Managing Other States - - [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md) - - [@Consume and @Provide](ts-other-states-consume-provide.md) - - [@Watch](ts-other-states-watch.md) - - About Rendering Control Syntax - - [if/else](ts-rending-control-syntax-if-else.md) - - [ForEach](ts-rending-control-syntax-foreach.md) - - [LazyForEach](ts-rending-control-syntax-lazyforeach.md) - - About @Component - - [build Function](ts-function-build.md) + + - Componentization - [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md) - [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md) - [Component Creation and Re-initialization](ts-component-creation-re-initialization.md) - - [About Syntactic Sugar](ts-syntactic-sugar.md) - Common Component Development Guidelines - [Button](ui-ts-basic-components-button.md) - [Web](ui-ts-components-web.md) - Common Layout Development Guidelines - - [Flex Layout](ui-ts-layout-flex.md) + - [Flexible Layout](ui-ts-layout-flex.md) - [Grid Layout](ui-ts-layout-grid-container.md) - [Media Query](ui-ts-layout-mediaquery.md) - Experiencing the Declarative UI @@ -74,9 +34,9 @@ - [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md) - [Recommendations for Improving Performance](ts-performance-improvement-recommendation.md) -- JavaScript-based Web-like Development Paradigm +- UI Development with JavaScript-compatible Web-like Development Paradigm - [Overview](ui-js-overview.md) - - Framework + - Framework Overview - [File Organization](js-framework-file.md) - ["js" Tag](js-framework-js-tag.md) - [app.js](js-framework-js-file.md) @@ -100,14 +60,14 @@ - [Defining Gesture Events](ui-js-building-ui-event.md) - [Defining Page Routes](ui-js-building-ui-routes.md) - Common Component Development Guidelines - - Container Components + - Container Component Development - [List Development](ui-js-components-list.md) - [Dialog Development](ui-js-components-dialog.md) - [Form Development](ui-js-components-form.md) - [Stepper Development](ui-js-components-stepper.md) - [Tabs Development](ui-js-component-tabs.md) - [Swiper Development](ui-js-components-swiper.md) - - Basic Components + - Basic Component Development - [Text Development](ui-js-components-text.md) - [Input Development](ui-js-components-input.md) - [Button Development](ui-js-components-button.md) @@ -128,8 +88,8 @@ - [CanvasRenderingContext2D](ui-js-components-canvasrenderingcontext2d.md) - [Path2D](ui-js-components-path2d.md) - [OffscreenCanvas](ui-js-components-offscreencanvas.md) - - [Grid-container Development](ui-js-components-grid.md) - - Svg + - [Grid Container Development](ui-js-components-grid.md) + - SVG Development - [Basics](ui-js-components-svg-overview.md) - [Graph Drawing](ui-js-components-svg-graphics.md) - [Path Drawing](ui-js-components-svg-path.md) diff --git a/en/application-dev/ui/arkui-overview.md b/en/application-dev/ui/arkui-overview.md index 43bff6f16355673a8bc4b027680e427b9801d4d3..5859e248d019b64d8e78886d8d4b5c518acf39b9 100644 --- a/en/application-dev/ui/arkui-overview.md +++ b/en/application-dev/ui/arkui-overview.md @@ -21,7 +21,7 @@ ArkUI is a UI development framework that provides what you'll need to develop ap - Drawing: ArkUI offers advanced drawing capabilities that allow you to draw custom shapes with a range of editors, from images to fill colors and texts. - Interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability. - Platform API channel: ArkUI provides an API extension mechanism through which platform capabilities are encapsulated to produce JavaScript APIs in a unified style. -- Two development paradigms: ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice. +- Two development paradigms: ArkUI comes with two development paradigms: eTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). You can choose whichever development paradigm that aligns with your practice. | Development Paradigm | Description | Applicable To | Intended Audience | | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/ui/figures/en-us_image_0000001118642600.PNG b/en/application-dev/ui/figures/en-us_image_0000001118642600.PNG new file mode 100644 index 0000000000000000000000000000000000000000..31839738950d995d6b8fd6046965d212c385436b Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001118642600.PNG differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001178084014.gif b/en/application-dev/ui/figures/en-us_image_0000001178084014.gif new file mode 100644 index 0000000000000000000000000000000000000000..0365a98883522861faf808d8e207ff287ccd4e22 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001178084014.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003489.gif b/en/application-dev/ui/figures/en-us_image_0000001276003489.gif deleted file mode 100644 index 0554bd02b6ce8c1d835a3cde3bf2427d8dd15bda..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001276003489.gif and /dev/null differ diff --git a/en/application-dev/ui/ts-application-states-apis-environment.md b/en/application-dev/ui/ts-application-states-apis-environment.md deleted file mode 100644 index 9da95fc0b83e5cb259e2233275075f734252e953..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-apis-environment.md +++ /dev/null @@ -1,34 +0,0 @@ -# Environment - - -Environment is a singleton object created by the framework when the application is started. It provides the AppStorage with a series of environment state attributes required by the application. These attributes describe the device environment where the application runs. Environment and its attributes are immutable, and all attribute values are of the simple type. The following example shows how to obtain the semantic environment from Environment: - - -```ts -Environment.EnvProp("accessibilityEnabled", "default"); -var enable = AppStorage.Get("accessibilityEnabled"); -``` - - -accessibilityEnabled is the default system variable identifier provided by Environment. You need to bind the corresponding system attribute to the AppStorage. Then, you can use the methods or decorators in the AppStorage to access the corresponding system attribute data. - - -## Environment APIs - -| key | Parameter | Return Value | Description | -| -------- | -------- | -------- | -------- | -| EnvProp | key: string,
defaultValue: any | boolean | Binds this system attribute to the AppStorage. You are advised to use this API during application startup. If the attribute already exists in the AppStorage, false is returned. Do not use the variables in the AppStorage. Instead, call this method to bind environment variables. | -| EnvProps | keys: {
key: string,
defaultValue: any
}[] | void | Associates this system item array with the AppStorage. | -| Keys | Array<string> | number | Returns the associated system item array. | - - -## Built-in Environment Variables - -| key | Type | Description | -| -------- | -------- | -------- | -| accessibilityEnabled | boolean | Whether to enable accessibility. | -| colorMode | ColorMode | Color mode. The options are as follows:
- **ColorMode.LIGHT**: light mode.
- **ColorMode.DARK**: dark mode. | -| fontScale | number | Font scale. The value range is [0.85, 1.45]. | -| fontWeightScale | number | Font weight scale. The value range is [0.6, 1.6]. | -| layoutDirection | LayoutDirection | Layout direction. The options are as follows:
- **LayoutDirection.LTR**: The direction is from left to right.
- **LayoutDirection.RTL**: The direction is from right to left. | -| languageCode | string | Current system language. The value is in lowercase, for example, zh. | diff --git a/en/application-dev/ui/ts-application-states-apis-persistentstorage.md b/en/application-dev/ui/ts-application-states-apis-persistentstorage.md deleted file mode 100644 index 8df5e76e2855c5f5d211aa35d87f54d19f5ce352..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-apis-persistentstorage.md +++ /dev/null @@ -1,48 +0,0 @@ -# PersistentStorage - - -ArkUI provides some static methods in the PersistentStorage class for managing persistent data of applications. Persistent data with specific tags can be linked to the AppStorage, and then the persistent data can be accessed through the AppStorage APIs. Alternatively, the @StorageLink decorator can be used to access the variable of the specific key. - - -| Name | Type | Return Value | Definition | -| -------- | -------- | -------- | -------- | -| PersistProp | key : string
defaultValue: T | void | Changes the associated named attribute to persistent data in the AppStorage. The value overwriting sequence is as follows:
- If the attribute exists in the AppStorage, use it to overwrite the value in Persistent.
- If Persistent contains the specified attribute, use the attribute value in Persistent.
- If the preceding conditions are not met, use defaultValue. The values null and undefined are not supported. | -| DeleteProp | key: string | void | Cancels two-way binding. The value of this attribute will be deleted from the persistent storage. | -| PersistProps | keys: {
key: string,
defaultValue: any
}[] | void | Associates multiple named attribute bindings. | -| Keys | void | Array <string> | Returns the flags of all persistent attributes. | - - -> **NOTE** -> -> - When using **PersistProp**, ensure that the input key exists in the AppStorage. -> -> - **DeleteProp** takes effect only for the data that has been linked during the current startup. - - -```ts -// xxx.ets -PersistentStorage.PersistProp("highScore", "0"); - -@Entry -@Component -struct PersistentComponent { - @StorageLink('highScore') highScore: string = '0' - @State currentScore: number = 0 - build() { - Column() { - if (this.currentScore === Number(this.highScore)) { - Text(`new highScore : ${this.highScore}`) - } - Button() { - Text(`goal!, currentScore : ${this.currentScore}`) - .fontSize(10) - }.onClick(() => { - this.currentScore++ - if (this.currentScore > Number(this.highScore)) { - this.highScore = this.currentScore.toString() - } - }) - } - } -} -``` diff --git a/en/application-dev/ui/ts-application-states-appstorage.md b/en/application-dev/ui/ts-application-states-appstorage.md deleted file mode 100644 index 5877f75ca55ad03cafb78eda50c0b26475f3033e..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-appstorage.md +++ /dev/null @@ -1,89 +0,0 @@ -# AppStorage - - -AppStorage is a singleton object in an application, which is created by the UI framework when the application is started and destroyed when the application exits. It is used to provide central storage for changing state attributes of an application. AppStorage contains all the state attributes that need to be accessed throughout the application. The AppStorage retains all attributes and their values as long as the application remains running, and the attribute values can be accessed through unique key values. - - -The UI component can synchronize the application state data with the AppStorage through the decorators. The application service logic can also be implemented by accessing the AppStorage through APIs. - - -The selection state attribute of the AppStorage can be synchronized with different data sources or data sinks. These data sources and data sinks can be local or remote devices and provide different functions, such as data persistence. Such data sources and data sinks can be implemented independently of the UI in the service logic. - - -By default, the attributes in the AppStorage are changeable. If needed, AppStorage can also use immutable (read-only) attributes. - - -## AppStorage APIs - -| Name | Type | Return Value | Definition | -| -------- | -------- | -------- | -------- | -| SetAndLink | key: string,
defaultValue: T | @Link | Works in a way similar to the Link API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Link instance corresponding to the default value is created and returned. | -| Set | key: string,
newValue: T | void | Replaces the value of a saved key. | -| Link | key: string | @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the AppStorage, and attribute changes made through the AppStorage will be synchronized to the variable or component. If the attribute with this key does not exist or is read-only, undefined is returned. | -| SetAndProp | propName: string,
defaultValue: S | @Prop | Works in a way similar to the Prop API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Prop instance corresponding to the default value is created and returned. | -| Prop | key: string | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the AppStorage will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the AppStorage. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, undefined is returned.
**NOTE**
The attribute value used in the prop method must be of a simple type. | -| SetOrCreate | key: string,
newValue: T | boolean | If an attribute that has the same name as the specified key exists: replaces the value of the attribute and returns true when the attribute can be modified; retains the original value of the attribute and returns false otherwise.
If an attribute that has the same name as the specified key does not exist: creates an attribute whose key is key and value is newValue. The values null and undefined are not supported. | -| Get | key: string | T or undefined | Obtains the value of the specified key. | -| Has | propName: string | boolean | Checks whether the attribute corresponding to the specified key value exists. | -| Keys | void | array<string> | Returns an array of strings containing all keys. | -| Delete | key: string | boolean | Deletes the key-value pair for the specified key. Returns true if the key-value pair exists and is successfully deleted; returns false otherwise. | -| Clear | void | boolean | Deletes all attributes. If any of the attributes is being referenced by a state variable, false is returned. | -| IsMutable | key: string | boolean | Specifies whether the attribute exists and can be changed. | - - -## Synchronization Between AppStorage and Components - -In [Managing Component States](ts-component-states-state.md), we have defined how to synchronize the state variables of child components with the @State decorated variables in the parent component or ancestor component, including @Prop, @Link, and @Consume. - -In this section, we'll describe how to synchronize component variables with the AppStorage through the @StorageLink and @StorageProp decorators. - - -### @StorageLink Decorator - -Two-way data binding can be established between components and the AppStorage through state variables decorated by @StorageLink(_key_). Wherein, key is the attribute key value in the AppStorage. When a component containing the @StorageLink decorated variable is created, the variable is initialized using the value in the AppStorage. Changes made to this variable in the component will be first synchronized to the AppStorage, and then to other bound instances, such as PersistentStorage or other bound UI components. - - -### @StorageProp Decorator - -One-way data binding can be established between components and the AppStorage through state variables decorated by @StorageProp(_key_). Wherein, key is the attribute key value in the AppStorage. When a component containing the @StorageProp decorated variable is created, the variable is initialized using the value in the AppStorage. Changes made to the value in the AppStorage will cause the bound UI component to update the state. - - -## Example - - -```ts -// xxx.ets - -@Entry -@Component -struct ComponentA { - @StorageLink('varA') varA: number = 2 - @StorageProp('languageCode') lang: string = 'en' - private label: string = 'count' - - aboutToAppear() { - this.label = (this.lang === 'en') ? 'Number' : 'Count' - } - - build() { - Row({ space: 20 }) { - - Button(`${this.label}: ${this.varA}`) - .onClick(() => { - AppStorage.Set('varA', AppStorage.Get('varA') + 1) - }) - Button(`lang: ${this.lang}`) - .onClick(() => { - if (this.lang === 'zh') { - AppStorage.Set('languageCode', 'en') - } else { - AppStorage.Set('languageCode', 'en') - } - this.label = (this.lang === 'en') ? 'Number' : 'Count' - }) - } - } -} -``` - -Each time the user clicks the **Count** button, the value of **this.varA** will increase by 1. This variable is synchronized with varA in the AppStorage. Each time the user clicks the language icon, the value of **languageCode** in the AppStorage will be changed, and the change will be synchronized to the **this.lang** variable. diff --git a/en/application-dev/ui/ts-attribution-configuration.md b/en/application-dev/ui/ts-attribution-configuration.md deleted file mode 100644 index 70d85aff0d3bb3a9b418753655ea33480bf681ff..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-attribution-configuration.md +++ /dev/null @@ -1,44 +0,0 @@ -# Attribute Configuration - - -Use attribute methods to configure component attributes. An attribute method follows the corresponding component and is bound to the component using the "." operator. - - -- The following is an example of configuring the font size attribute of the Text component: - - ```ts - Text('123') - .fontSize(12) - ``` - - -- Use the "." operator to implement chain call to configure multiple attributes at the same time, as shown below: - - ```ts - Image('a.jpg') - .alt('error.jpg') - .width(100) - .height(100) - ``` - - -- In addition to constants, you can also pass variables or expressions, as shown below: - - ```ts - // Size, count, and offset are private variables defined in the component. - Text('hello') - .fontSize(this.size) - Image('a.jpg') - .width(this.count % 2 === 0 ? 100 : 200) - .height(this.offset + 100) - ``` - - -- For attributes of preset components, the framework also provides some predefined enumeration types, which you can pass as parameters to methods. Enumeration types must meet the parameter type requirements on the enumeration type definitions for specific attributes. You can configure the font color and weight attributes of the Text component as follows: - - ```ts - Text('hello') - .fontSize(20) - .fontColor(Color.Red) - .fontWeight(FontWeight.Bold) - ``` diff --git a/en/application-dev/ui/ts-child-component-configuration.md b/en/application-dev/ui/ts-child-component-configuration.md deleted file mode 100644 index c2fe0c68c3b49e09091be56505cae0bea9e370fb..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-child-component-configuration.md +++ /dev/null @@ -1,49 +0,0 @@ -# Child Component Configuration - - -For a component that supports child components, for example, a container component, add the UI descriptions of the child components inside "{ ... }". The **\**, **\**, **\**, **\