diff --git a/CODEOWNERS b/CODEOWNERS index 8914fcf1ec8cc5ec63e710e9a9bbc511956cbb11..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 @@ -165,10 +167,9 @@ zh-cn/application-dev/reference/arkui-ts/ @HelloCrease zh-cn/application-dev/reference/native-apis @RayShih zh-cn/application-dev/reference/native-lib @RayShih zh-cn/application-dev/quick-start/start-overview.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets.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/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 @@ -177,64 +178,25 @@ zh-cn/application-dev/napi/napi-guidelines.md @RayShih zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease -zh-cn/application-dev/website.md @zengyawen zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/file-management/ @qinxiaowang zh-cn/application-dev/application-test/ @HelloCrease +zh-cn/application-dev/device-usage-statistics/ @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-DataUriUtils.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md @RayShih -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-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/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 @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 @@ -302,7 +264,6 @@ 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 @RayShih zh-cn/application-dev/reference/apis/js-apis-wifiext.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-accessibility.md @RayShih zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hichecker.md @zengyawen @@ -316,7 +277,7 @@ zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-system-time.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-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 @@ -365,57 +326,46 @@ 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/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 @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen -zh-cn/application-dev/reference/apis/Readme-CN.md @zengyawen zh-cn/application-dev/reference/apis/development-intro.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-Metadata.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-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-continuation-continuationExtraParams.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-continuation-continuationResult.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-dispatchInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-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-errorManager.md @RayShih zh-cn/application-dev/reference/apis/js-apis-inputevent.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @RayShih zh-cn/application-dev/reference/apis/js-apis-keycode.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-keyevent.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-logs.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-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-processrunninginformation.md @RayShih zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-system-app.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-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 @@ -424,20 +374,19 @@ zh-cn/application-dev/reference/apis/js-apis-system-device.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-system-file.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-system-location.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-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 -zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @HelloCrease +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 +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-application-quickFixManager.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-bundle-PackInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-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 @@ -447,3 +396,64 @@ 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/en/application-dev/ability/context-userguide.md b/en/application-dev/ability/context-userguide.md index 4abf217eee28052d3163d32aa0bce18893e1df08..d5cd52e64ed5064ded90efea7d60898e1c2ee96c 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability/context-userguide.md @@ -235,13 +235,13 @@ export default class MainAbility extends Ability { For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). -### Obtaining the Context on an eTS Page +### Obtaining the Context on an ArkTS Page -In the stage model, in the `onWindowStageCreate` lifecycle of an ability, you can call `SetUIContent` of `WindowStage` to load an eTS page. In some scenarios, you need to obtain the context on the page to call related APIs. +In the stage model, in the `onWindowStageCreate` lifecycle of an ability, you can call `SetUIContent` of `WindowStage` to load an ArkTS page. In some scenarios, you need to obtain the context on the page to call related APIs. **How to Obtain** -Use the API described in the table below to obtain the context associated with an eTS page. +Use the API described in the table below to obtain the context associated with an ArkTS page. | API | Description | | :------------------------------------ | :--------------------------- | diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 48270359d9d49f9ea7d7111b021cd8b81da3df82..3bafb0bc097f0277f88ff4489c2731afdad6569e 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -92,7 +92,7 @@ After the preceding code is executed, the **startAbility()** API is called to st - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. - If the Service ability is running, the system directly calls **onCommand()** on the Service ability. -The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability-applying-only-to-system-applications). +The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability). ```javascript import featureAbility from '@ohos.ability.featureAbility'; diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 6ddf26b87022c8bf098efc72de9ae4b4c0e28779..da1a7e1c517f284037a41a88e2167b6d1d2406aa 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -12,7 +12,7 @@ To use related APIs, you must declare the **ohos.permission.INTERNET** permissio For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md). -The following table describes the related APIs. +The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). | API | Description | | ----------------------------------------- | --------------------------------------------------------- | diff --git a/en/application-dev/device/device-location-overview.md b/en/application-dev/device/device-location-overview.md index aa619c4549083521dd6ac5bcc05795074adc9af4..a26f0c5a7003a14c13cf4fc697e3a55a202f1eec 100644 --- a/en/application-dev/device/device-location-overview.md +++ b/en/application-dev/device/device-location-overview.md @@ -15,15 +15,18 @@ Your application can call location-specific APIs to obtain the location informat Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors. - **Coordinate** + A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. - **GNSS positioning** GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. - **Base station positioning** + Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. - **WLAN or Bluetooth positioning** + WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. diff --git a/en/application-dev/device/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/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index dc45ed9db0eec504b1ff6f535babf11265f2df91..c0b69b85a868f8afd7a7f627fb0275f46cbc87fc 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -1,19 +1,15 @@ # FAQs - [Ability Framework Development](faqs-ability.md) -- [Data Management Development](faqs-data-management.md) -- [File Management Development](faqs-file-management.md) -- [Graphics and Image Development](faqs-graphics.md) -- [hdc_std Command Usage](faqs-ide.md) -- [IDE Usage](faqs-hdc-std.md) - [ArkUI (JavaScript) Development](faqs-ui-js.md) - [ArkUI (eTS) Development](faqs-ui-ets.md) - [Graphics and Image Development](faqs-graphics.md) - [File Management Development](faqs-file-management.md) +- [Network and Connection Development](faqs-connectivity.md) - [Data Management Development](faqs-data-management.md) - [Device Management Development](faqs-device-management.md) - [Native API Usage](faqs-native.md) -- [Network and Connection Development](faqs-connectivity.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) +- [hdc_std Command Usage](faqs-ide.md) +- [IDE Usage](faqs-hdc-std.md) - [Development Board](faqs-development-board.md) - diff --git a/en/application-dev/faqs/faqs-connectivity.md b/en/application-dev/faqs/faqs-connectivity.md index 3b8dea82129c03f0dc12c12296a28b9a0c46c99b..e3b02269e2de947fb4ab4069f1d7ba4812825ddc 100644 --- a/en/application-dev/faqs/faqs-connectivity.md +++ b/en/application-dev/faqs/faqs-connectivity.md @@ -19,7 +19,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 -Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a libcurl library operation timeout. For details, see any HTTP status code description available. +Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 4c293fdee7114866ebd969151c0914d29a144941..62bf66fd7cabb7e30c765126ddacba639bd951f5 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -9,15 +9,15 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | -| ohos.i18n | getSystemRegion(): string | Obtains the system region. | -| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | -| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | -| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | -| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | +| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | +| ohos.i18n | getSystemRegion(): string | Obtains the system region. | +| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | +| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | +| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | +| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | +| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | ### How to Develop @@ -26,7 +26,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). - + ```js var language = i18n.getSystemLanguage(); ``` @@ -42,7 +42,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Obtain the system locale. Call the **getSystemLocale** method to obtain the system locale. - + ```js var locale = i18n.getSystemLocale(); ``` @@ -51,7 +51,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **isRTL** method to check whether the locale's language is RTL. - + ```js var rtl = i18n.isRTL("zh-CN"); ``` @@ -67,7 +67,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Obtain the localized display of a language. Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var language = "en"; var locale = "zh-CN"; @@ -78,7 +78,7 @@ You can use APIs provided in the following table to obtain the system language a 7. Obtain the localized display of a country. Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var country = "US"; var locale = "zh-CN"; @@ -116,7 +116,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - + ```js var calendar = i18n.getCalendar("zh-CN", "gregory"); ``` @@ -135,7 +135,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Set the year, month, day, hour, minute, and second for the **Calendar** object. Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` @@ -144,7 +144,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. - + ```js calendar.setTimeZone("Asia/Shanghai"); var timezone = calendar.getTimeZone(); @@ -163,7 +163,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Set and obtain the minimum count of days in the first week for the **Calendar** object. Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - + ```js calendar.setMinimalDaysInFirstWeek(3); var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); @@ -173,7 +173,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. - + ```js var localizedName = calendar.getDisplayName("zh-CN"); ``` @@ -196,11 +196,11 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | -| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | -| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | +| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | +| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | +| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | ### How to Develop @@ -209,7 +209,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. - + ```js var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); ``` @@ -223,7 +223,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Format a phone number. Call the **format** method of **PhoneNumberFormat** to format the input phone number. - + ```js var formattedNumber = phoneNumberFormat.format("15812341234"); ``` @@ -236,15 +236,15 @@ The **unitConvert** API is provided to help you implement measurement conversion ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | +| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | ### How to Develop 1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert8) method to convert a measurement unit and format the display result. + Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result. ```js @@ -254,7 +254,7 @@ The **unitConvert** API is provided to help you implement measurement conversion var locale = "en-US"; var style = "long"; i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); - ``` + ``` ## Alphabet Index @@ -278,7 +278,7 @@ The **unitConvert** API is provided to help you implement measurement conversion Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - + ```js var indexUtil = i18n.getInstance("zh-CN"); ``` @@ -294,7 +294,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 3. Add an index. Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - + ```js indexUtil.addLocale("ar") ``` @@ -302,7 +302,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 4. Obtain the index of a string. Call the **getIndex** method to obtain the alphabet index of a string. - + ```js var text = "access index"; indexUtil.getIndex(text); @@ -336,7 +336,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **getLineInstance** method to instantiate a **BreakIterator** object. - + ```js var locale = "en-US" var breakIterator = i18n.getLineInstance(locale); @@ -357,7 +357,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. - + ```js var pos = breakIterator.current(); ``` @@ -383,7 +383,9 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. - + ```js var isboundary = breakIterator.isBoundary(5); ``` + + ``` \ No newline at end of file diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 424320dcc17f3dc0eb6d3e30970869da83874408..540e8dbf89029df9daa4825c5883eb7d41271412 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -13,13 +13,13 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | -| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | -| ohos.intl | toString(): string | Converts locale information into a string. | -| ohos.intl | maximize(): Locale | Maximizes locale information. | -| ohos.intl | minimize(): Locale | Minimizes locale information. | +| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | +| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | +| ohos.intl | toString(): string | Converts locale information into a string. | +| ohos.intl | maximize(): Locale | Maximizes locale information. | +| ohos.intl | minimize(): Locale | Minimizes locale information. | ### How to Develop @@ -81,13 +81,13 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to f ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | ### How to Develop @@ -144,12 +144,12 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to forma ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | +| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | +| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | ### How to Develop @@ -195,12 +195,12 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **Collator** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | -| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | +| ohos.intl | constructor()8+ | Creates a **Collator** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | +| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | +| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | ### How to Develop @@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings var collator = new intl.Collator(); ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). ```js var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); @@ -246,11 +246,11 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | -| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | +| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | +| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | ### How to Develop @@ -264,7 +264,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ var pluralRules = new intl.PluralRules(); ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). ```js var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); @@ -287,13 +287,13 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | ### How to Develop @@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) var relativeTimeFormat = new intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). ```js var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 280efd8afa5fa845dab0d607ed94b33e2a75e6d3..bf16d91435bf68ebd6f93a1a52b5f6da35e67169 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -4,5 +4,6 @@ - [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) - [Native Window Development](native-window-guidelines.md) +- [Using MindSpore Lite for Model Inference](native-window-guidelines.md) diff --git a/en/application-dev/napi/figures/01.png b/en/application-dev/napi/figures/01.png new file mode 100644 index 0000000000000000000000000000000000000000..5293e5afe5a8637dbef3fd0b32c7bd43d60e4368 Binary files /dev/null and b/en/application-dev/napi/figures/01.png differ diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..47ede475575484d60317e9ed7e2afe586fb12524 --- /dev/null +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -0,0 +1,216 @@ +# Using MindSpore Lite for Model Inference + +## When to Use + +MindSpore Lite is an AI engine that provides AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition. + +This document describes the general development process for MindSpore Lite model inference. + +## Basic Concepts + +Before getting started, you need to understand the following basic concepts: + +**Tensor**: a special data structure that is similar to arrays and matrices. It is a basic data structure used in MindSpore Lite network operations. + +**Float16 inference**: a mode in which Float16 is used for inference. Float16, also called half-precision, uses 16 bits to represent a number. + + + +## Available APIs +APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. +### Context APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| +|void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| +|OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| +|void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| +|void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| +|void OH_AI_ContextAddDeviceInfo(OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info)|Adds a runtime device information object.| + +### Model APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ModelHandle OH_AI_ModelCreate()|Creates a model object.| +|OH_AI_Status OH_AI_ModelBuildFromFile(OH_AI_ModelHandle model, const char *model_path,OH_AI_ModelType odel_type, const OH_AI_ContextHandle model_context)|Loads and builds a MindSpore model from a model file.| +|void OH_AI_ModelDestroy(OH_AI_ModelHandle *model)|Destroys a model object.| + +### Tensor APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_TensorHandleArray OH_AI_ModelGetInputs(const OH_AI_ModelHandle model)|Obtains the input tensor array structure of a model.| +|int64_t OH_AI_TensorGetElementNum(const OH_AI_TensorHandle tensor)|Obtains the number of tensor elements.| +|const char *OH_AI_TensorGetName(const OH_AI_TensorHandle tensor)|Obtains the name of a tensor.| +|OH_AI_DataType OH_AI_TensorGetDataType(const OH_AI_TensorHandle tensor)|Obtains the tensor data type.| +|void *OH_AI_TensorGetMutableData(const OH_AI_TensorHandle tensor)|Obtains the pointer to variable tensor data.| + +## How to Develop +The following figure shows the development process for MindSpore Lite model inference. + +**Figure 1** Development process for MindSpore Lite model inference +![how-to-use-mindspore-lite](figures/01.png) + +The development process consists of the following main steps: + +1. Prepare the required model. + + The required model can be downloaded directly or obtained using the model conversion tool. + + - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example. + - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format. + +2. Create a context, and set parameters such as the number of runtime threads and device type. + + ```c + // Create a context, and set the number of runtime threads to 2 and the thread affinity mode to 1 (big cores first). + OH_AI_ContextHandle context = OH_AI_ContextCreate(); + if (context == NULL) { + printf("OH_AI_ContextCreate failed.\n"); + return OH_AI_STATUS_LITE_ERROR; + } + const int thread_num = 2; + OH_AI_ContextSetThreadNum(context, thread_num); + OH_AI_ContextSetThreadAffinityMode(context, 1); + // Set the device type to CPU, and disable Float16 inference. + OH_AI_DeviceInfoHandle cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU); + if (cpu_device_info == NULL) { + printf("OH_AI_DeviceInfoCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + OH_AI_DeviceInfoSetEnableFP16(cpu_device_info, false); + OH_AI_ContextAddDeviceInfo(context, cpu_device_info); + ``` + +3. Create, load, and build the model. + + Call **OH_AI_ModelBuildFromFile** to load and build the model. + + In this example, the **argv[1]** parameter passed to **OH_AI_ModelBuildFromFile** indicates the specified model file path. + + ```c + // Create a model. + OH_AI_ModelHandle model = OH_AI_ModelCreate(); + if (model == NULL) { + printf("OH_AI_ModelCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + + // Load and build the model. The model type is OH_AI_ModelTypeMindIR. + int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_ModelTypeMindIR, context); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelBuildFromFile failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +4. Input data. + + Before executing model inference, you need to populate data to the input tensor. In this example, random data is used to populate the model. + + ```c + // Obtain the input tensor. + OH_AI_TensorHandleArray inputs = OH_AI_ModelGetInputs(model); + if (inputs.handle_list == NULL) { + printf("OH_AI_ModelGetInputs failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + // Use random data to populate the tensor. + ret = GenerateInputDataWithRandom(inputs); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("GenerateInputDataWithRandom failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +5. Execute model inference. + + Call **OH_AI_ModelPredict** to perform model inference. + + ```c + // Execute model inference. + OH_AI_TensorHandleArray outputs; + ret = OH_AI_ModelPredict(model, inputs, &outputs, NULL, NULL); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelPredict failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +6. Obtain the output. + + After model inference is complete, you can obtain the inference result through the output tensor. + + ```c + // Obtain the output tensor and print the information. + for (size_t i = 0; i < outputs.handle_num; ++i) { + OH_AI_TensorHandle tensor = outputs.handle_list[i]; + int64_t element_num = OH_AI_TensorGetElementNum(tensor); + printf("Tensor name: %s, tensor size is %zu ,elements num: %lld.\n", OH_AI_TensorGetName(tensor), + OH_AI_TensorGetDataSize(tensor), element_num); + const float *data = (const float *)OH_AI_TensorGetData(tensor); + printf("output data is:\n"); + const int max_print_num = 50; + for (int j = 0; j < element_num && j <= max_print_num; ++j) { + printf("%f ", data[j]); + } + printf("\n"); + } + ``` + +7. Destroy the model. + + If the MindSpore Lite inference framework is no longer needed, you need to destroy the created model. + + ```c + // Destroy the model. + OH_AI_ModelDestroy(&model); + ``` + +## Verification + +1. Compile **CMakeLists.txt**. + + ```cmake + cmake_minimum_required(VERSION 3.14) + project(Demo) + + add_executable(demo main.c) + + target_link_libraries( + demo + mindspore-lite.huawei + pthread + dl + ) + ``` + - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.cmake"`. + + - The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`. + +2. Run the CMake tool. + + - Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board. + - Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command: + + ```shell + ./demo mobilenetv2.ms + ``` + + The inference is successful if the output is similar to the following: + + ```shell + # ./QuickStart ./mobilenetv2.ms + Tensor name: Softmax-65, tensor size is 4004 ,elements num: 1001. + output data is: + 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 + ``` diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index f471f4a6eed7d3eb2c96dab8cae4cb7480a13616..188b4f1336e2c56562f594e42dc26cabf8a8fc55 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -17,11 +17,11 @@ You can `import` the native .so that contains the JS processing logic. For examp ### .so Naming Rules -Each module has a .so file. For example, if the module name is `hello`, name the .so file **libhello.so**. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. +Each module has a .so file. For example, if the module name is `hello`, name the .so file `libhello.so`. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. ### JS Objects and Threads -The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. +The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. Observe the following rules: * The NAPIs can be used only in JS threads. * **env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread. @@ -640,8 +640,3 @@ export default { } } ``` -## Samples -The following samples are provided for native API development: -- [`NativeAPI`: NativeAPI (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) -- [First Native C++ Application (eTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) -- [Native Component (eTS) (API9) ](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index 37d55ef434d0cec71eed60862e13f1de0d9e13fb..dfb611ea572b80486756faaa4b004513cd6858a7 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -32,7 +32,8 @@ import commonEvent from '@ohos.commonEvent'; 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). ```js -private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Used to save the created subscriber object for subsequent subscription and unsubscription. +private subscriber = null // Subscriber information var subscribeInfo = { diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md index b1df6ce3e2c022accb06bc1070740b7d7b3e7433..75237412fdf29d88843a9f23fa653f64f2de7c86 100644 --- a/en/application-dev/notification/notification-brief.md +++ b/en/application-dev/notification/notification-brief.md @@ -1,6 +1,6 @@ # Common Event and Notification Overview -The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, or warning information. +The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more. Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. diff --git a/en/application-dev/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/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-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-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-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-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index eb85e5d52d50068b8147c1a4789389b2cf5506e1..d744a5ab3e1ef6770d0dee18d68c4a1512cd4183 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,40 +1,40 @@ # BundleInfo +The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. + > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - ## BundleInfo **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Bundle name. | -| type | string | Yes | No | Bundle type. | -| appId | string | Yes | No | ID of the application to which the bundle belongs. | -| uid | number | Yes | No | UID of the application to which the bundle belongs. | -| installTime | number | Yes | No | Time when the HAP file was installed. | -| updateTime | number | Yes | No | Time when the HAP file was updated. | -| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | +| name | string | Yes | No | Bundle name. | +| type | string | Yes | No | Bundle type. | +| appId | string | Yes | No | ID of the application to which the bundle belongs. | +| uid | number | Yes | No | UID of the application to which the bundle belongs. | +| installTime | number | Yes | No | Time when the HAP file was installed. | +| updateTime | number | Yes | No | Time when the HAP file was updated. | +| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| | reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | -| versionName | string | Yes | No | Version description of the bundle. | -| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | -| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | -| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | -| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | +| vendor | string | Yes | No | Vendor of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | +| versionName | string | Yes | No | Version description of the bundle. | +| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | +| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | +| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | +| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | | extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.
The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.| @@ -45,8 +45,8 @@ Provides the detailed information of the permissions to request from the system. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------------------- | ----------------------- | ---- | ---- | -------------------- | +| Name | Type | Readable| Writable| Description | +| --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId9+ | number | Yes | Yes | ID of the reason for requesting the permission.| @@ -60,7 +60,7 @@ Describes the application scenario and timing for using the permission. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------- | -------------- | ---- | ---- | ------------------------- | +| Name | Type | Readable| Writable| Description | +| --------- | -------------- | ---- | ---- | --------------------------- | | abilities | Array\ | Yes | Yes | Abilities that use the permission.| | when | string | Yes | Yes | Time when the permission is used. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..323d4d1f948d12193b38333a11f7954153fec97a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md @@ -0,0 +1,157 @@ +# PackInfo + +The **PackInfo** module provides the bundle package information, which can be obtained using [bundle.getBundlePackInfo](js-apis-Bundle.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## BundlePackFlag + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Value | Description | +| ------------------ | ---------- | ---------------------------------- | +| GET_PACK_INFO_ALL | 0x00000000 | All information about the package. | +| GET_PACKAGES | 0x00000001 | Package information about the package.| +| GET_BUNDLE_SUMMARY | 0x00000002 | Bundle summary of the package. | +| GET_MODULE_SUMMARY | 0x00000004 | Module summary of the package. | + +## BundlePackInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------- | --------------------------------------- | ---- | ---- | ----------------------------- | +| packages | Array\<[PackageConfig](#packageconfig)> | Yes | No | Package configuration information. | +| summary | [PackageSummary](#packagesummary) | Yes | No | Package summary.| + +## PackageConfig + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| deviceType | Array\ | Yes | No | Device types supported. | +| name | string | Yes | No | Package name. | +| moduleType | string | Yes | No | Module type. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| + +## PackageSummary + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | --------------------------------------------- | ---- | ---- | -------------------- | +| app | [BundleConfigInfo](#bundleconfiginfo) | Yes | No | Bundle configuration information. | +| modules | Array\<[ModuleConfigInfo](#moduleconfiginfo)> | Yes | No | Module configuration information.| + +## BundleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ---------- | ------------------- | ---- | ---- | ---------------------------------- | +| bundleName | string | Yes | No | Bundle name of an application. It uniquely identifies the application.| +| version | [Version](#version) | Yes | No | Bundle version. | + +## ModuleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------ | ------------------------------------------------- | ---- | ---- | ---------------------------------- | +| apiVersion | [ApiVersion](#apiversion) | Yes | No | API version of the module. | +| deviceType | Array\ | Yes | No | Device type of the module. | +| distro | [ModuleDistroInfo](#moduledistroinfo) | Yes | No | Distribution information of the module. | +| abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | Yes | No | Ability information of the module. | +| extensionAbilities | Array\<[ExtensionAbilities](#extensionabilities)> | Yes | No | Extension ability information of the module.| + +## ModuleDistroInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | +| mainAbility | string | Yes | No | Name of the main ability. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| +| installationFree | boolean | Yes | No | Whether the HAP file supports the installation-free feature. The value **true** means that the HAP file supports the installation-free feature and meets installation-free constraints, and **false** means the opposite.| +| moduleName | string | Yes | No | Module name. | +| moduleType | string | Yes | No | Module type. | + +## ModuleAbilityInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Logical name of the ability. The name must be unique in the application. | +| label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.| +| visible | boolean | Yes | No | Whether the ability can be called by other applications. The value **true** means that the ability can be called by other applications, and **false** means the opposite.| +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. | + +## ExtensionAbilities + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Specification of the widget. A widget is a brief view of an application that is embedded on the home screen to receive periodical updates.| + +## AbilityFormInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Widget name. | +| type | string | Yes | No | Widget type. | +| updateEnabled | boolean | Yes | No | Whether the widget supports periodical update. The value **true** means that the widget supports periodical update, and **false** means the opposite.| +| scheduledUpdateTime | string | Yes | No | Scheduled time to update the widget. The value is in 24-hour format and accurate to the minute. | +| updateDuration | number | Yes | No | Interval to update the widget. The unit is 30 minutes. The value is a multiple of 30. A widget can be updated periodically, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). If both are configured, **updateDuration** takes precedence.| +| supportDimensions | Array\ | Yes | No | Dimensions of the widget. The value can be **1\*2**, **2\*2**, **2\*4**, **4\*4**, or a combination of these options. At least one option must be specified when defining the widget.| +| defaultDimension | number | Yes | No | Default dimensions of the widget. The value must be available in the **supportDimensions** array of the widget.| + +## ApiVersion + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | -------------------- | +| releaseType | string | Yes | No | Name of the API version. | +| compatible | number | Yes | No | Minimum API version.| +| target | numbe | Yes | No | Target API version. | + +## Version + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| minCompatibleVersionCode | number | Yes | No | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario. The value is a 32-bit non-negative integer.| +| name | string | Yes | No | Application version number visible to users. | +| code | number | Yes | No | Application version number used only for application management. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version.| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 5ea820e6160af090dbaf1e784970adfcb01ba013..ab561f552758ed5af3c79bc2c4406d84ceb56f2b 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -827,7 +827,7 @@ call.reject(1, (error, data) => { ## call.reject7+ -reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback\): void +reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 9168a42e978c20caaface2523337d8c413a2296e..b4f3906b02b1dea7dabd558173010a37e65c2c19 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,6 +1,6 @@ # Standard NFC Card Emulation -The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. +The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). > **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,6 +12,17 @@ The **cardEmulation** module implements Near-Field Communication (NFC) card emul import cardEmulation from '@ohos.nfc.cardEmulation'; ``` +## FeatureType + +Enumerates the NFC card emulation types. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| HCE | 0 | HCE.| +| UICC | 1 | Subscriber identity module (SIM) card emulation.| +| ESE | 2 | embedded Secure Element (eSE) emulation.| ## cardEmulation.isSupported @@ -19,23 +30,31 @@ isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ----------------------- | +| feature | number | Yes | Card emulation type. For details, see [FeatureType](#featuretype).| + **Return value** | **Type**| **Description**| | -------- | -------- | - | boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.| + | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ -Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance. +Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE. ### startHCE8+ startHCE(aidList: string[]): boolean -Starts HCE. +Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -45,13 +64,13 @@ Starts HCE. | Name | Type | Mandatory| Description | | ------- | -------- | ---- | ----------------------- | -| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| +| aidList | string[] | Yes | AID list to register.| ### stopHCE8+ stopHCE(): boolean -Stops HCE. +Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -61,7 +80,7 @@ Stops HCE. on(type: "hceCmd", callback: AsyncCallback): void; -Subscribes to messages from the peer device after **startHCE()**. +Registers a callback to receive APDUs from the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -72,13 +91,13 @@ Subscribes to messages from the peer device after **startHCE()**. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------------- | | type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | -| callback | AsyncCallback | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).| +| callback | AsyncCallback | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.| ### sendResponse8+ sendResponse(responseApdu: number[]): void; -Sends a response to the peer device. +Sends a response to the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -88,16 +107,25 @@ Sends a response to the peer device. | Name | Type | Mandatory| Description | | ------------ | -------- | ---- | -------------------------------------------------- | -| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.| +| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. Each number of the APDU is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js +import cardEmulation from '@ohos.nfc.cardEmulation'; + +var isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE); +if (!isHceSupported) { + console.log('this device is not supported for HCE, ignore it.'); + return; +} + +// The device supports HCE and transimits APDUs with the remote NFC reader. var hceService = new cardEmulation.HceService(); hceService.startHCE([ "F0010203040506", "A0000000041010" -]) -hceService.stopHCE(); +]); + hceService.on("hceCmd", (err, res) => { if(err.data === 0) { console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); @@ -108,4 +136,7 @@ hceService.on("hceCmd", (err, res) => { console.log('callback => Operation hceCmd failed. Cause: ' + err.data); } }) + +// Stop HCE when the application exits the NFC card emulation. +hceService.stopHCE(); ``` diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 50fad38058530104fda01f09d5745c0f8051000a..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 67b846c17b94a6acee894da72ae28cedefd2532c..a166781108683f6b6fb53673da4deacd99882b26 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -202,8 +202,8 @@ Updates a contact based on the specified contact information and attributes. Thi contact.updateContact({ name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] - },{ - attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] + }, { + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err) => { if (err) { console.log('updateContact callback: err->${JSON.stringify(err)}'); @@ -432,7 +432,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn ```js contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryMyCard callback: err->${JSON.stringify(err)}`); @@ -469,7 +469,7 @@ Queries my card based on the specified contact attributes. This API uses a promi ```js let promise = contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryMyCard success: data->${JSON.stringify(data)}`); @@ -487,7 +487,7 @@ Selects a contact. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Parameters** @@ -516,7 +516,7 @@ Selects a contact. This API uses a promise to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Return Value** diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 6398b87f685e5f91c59dacb1da97b4ad993e5afa..0bc6f9c6a4c156cfa2d604885572fcbe4bdc41bc 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -16,19 +16,6 @@ import emitter from '@ohos.events.emitter' None -## EventPriority - -Enumerates the event emit priority levels. - -**System capability**: SystemCapability.Notification.Emitter - -| Name | Value | Description | -| --------- | ---- | ------------------------------------------------- | -| IMMEDIATE | 0 | The event will be emitted immediately. | -| HIGH | 1 | The event will be emitted before low-priority events. | -| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority. | -| IDLE | 3 | The event will be emitted after all the other events. | - ## emitter.on on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata)\>): void @@ -39,21 +26,21 @@ Subscribes to an event in persistent manner. This API uses a callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('callback'); -}; -emitter.on(innerEvent, callback); +} +emitter.on(innerEvent, EmitterCallback); ``` ## emitter.once @@ -66,21 +53,21 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('once callback'); }; -emitter.once(innerEvent, callback); +emitter.once(innerEvent, EmitterCallback); ``` ## emitter.off @@ -121,18 +108,31 @@ Emits an event to the event queue. **Example** ```javascript -var eventData = { +let eventData = { data: { "content": "c", "id": 1, }}; -var innerEvent = { +let innerEvent = { eventId: 1, priority: emitter.EventPriority.HIGH }; emitter.emit(innerEvent, eventData); ``` +## EventPriority + +Enumerates the event emit priority levels. + +**System capability**: SystemCapability.Notification.Emitter + +| Name | Value | Description | +| --------- | ---- | --------------------------------------------------- | +| IMMEDIATE | 0 | The event will be emitted immediately. | +| HIGH | 1 | The event will be emitted before low-priority events. | +| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority.| +| IDLE | 3 | The event will be emitted after all the other events. | + ## InnerEvent Describes an in-process event. @@ -141,7 +141,7 @@ Describes an in-process event. | Name | Type | Readable| Writable| Description | | -------- | ------------------------------- | ---- | ---- | ---------------------------------- | -| eventId | number | Yes | Yes | Event ID, which is used to identify an event.| +| eventId | number | Yes | Yes | Event ID.| | priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event. | ## EventData diff --git a/en/application-dev/reference/apis/js-apis-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-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md deleted file mode 100644 index b80660185cffaf10993bf9c54ba1f88a1f16b7f4..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ /dev/null @@ -1,282 +0,0 @@ -# User File Access and Management - -The **fileManager** module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. - ->**NOTE**
-> ->- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**. - -## Modules to Import - -```js -import filemanager from '@ohos.fileManager'; -``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> - -Obtains information about the root album or directory in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<[FileInfo](#fileinfo)[]> | Promise used to return the root album or directory information obtained.| - -**Example** - - ```js - filemanager.getRoot().then((fileInfos) => { - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }).catch((err) => { - console.log(err) - }); - ``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) : void - -Obtains information about the root album or directory in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Example** - - ```js - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.getRoot(options, (err, fileInfos)=>{ - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}) : Promise<FileInfo[]> - -Obtains information about the second-level album or files in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| path | string | Yes| URI of the directory to query.| -| type | string | Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<FileInfo[]> | Promise used to return the album or file information obtained.| - -**Error** - -| Error Info| Error Code|Description| -| -- | --- | -- | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service.| -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Obtain all files in the directory. You can use getRoot to obtain the directory URI. - filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "file_folder"); - let path = file.path; - filemanager.listFile(path, "file").then((files) => { - console.log("files:" + JSON.stringify(files)); - }).catch((err) => { - console.log("failed to get files" + err); - }); - }).catch((err) => { - console.log("failed to get root" + err); - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}, callback : AsyncCallback<FileInfo[]>) : void - -Obtains information about the second-level album or files in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | URI of the directory to query. | -| type | string | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Error** - -| Error Info | Error Code| Description | -| ------------------------- | ------ | ------------------------- | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service. | -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - -```js -// Obtain all files in the directory. You can use getRoot to obtain the directory URI. -filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "image_album"); - let path = file.path; - filemanager.listFile(path, "image",function(err, files){ - console.log("files:" + JSON.stringify(files)); - }) -}).catch((err) => { - console.log("failed to get root" + err); -}); -``` - -## filemanager.createFile - -createFile(path : string, filename : string, options? : {dev? : DevInfo}) : Promise<string> - -Creates a file in the specified path in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| filename | string | Yes| Name of the file to create.| -| path | string | Yes| URI of the file to create.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<string> | Promise used to return the URI of the file created.| - -**Error** - -| Error Info| Error Code|Description| -| -- | --- | -- | -| Operation not permitted | 1 | A file with the same name already exists.| -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service.| -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Create a file. - let media_path = "" // Obtain the file URI using listFile() and getRoot(). - let name = "xxx.jpg" // File to be saved. - filemanager.createFile(media_path, name).then((uri) => { - // The URI of the file created is returned. - console.log("file uri:"+uri); - }).catch((err) => { - console.log(err); - }); - ``` - -## filemanager.createFile - -createFile(path : string, filename: string, options? : {dev? : DevInfo}, callback : AsyncCallback<string>) : void - -Creates a file in the specified path in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| filename | string | Yes | Name of the file to create. | -| path | string | Yes | URI of the file to create. | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Error** - -| Error Info | Error Code| Description | -| ------------------------- | ------ | ------------------------- | -| Operation not permitted | 1 | A file with the same name already exists. | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service. | -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Create a file. - // Call listFile() and getRoot() to obtain the file URI. - let media_path = "" - // File to be saved. - let name = "xxx.jpg" - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.createFile(media_path, name, options, function(err, uri) { - // The URI of the file created is returned. - console.log("file uri:"+uri); - }); - - ``` - -## FileInfo -Defines the file information returned by **getRoot()** or **listFile()**. - -**System capability**: SystemCapability.FileManagement.UserFileService - -### Attributes - -| Name| Type| Readable| Writable| Description| -| --- | -- | -- | -- | -- | -| name | string | Yes| No| File name.| -| path | string | Yes| No| URI of the file.| -| type | string | Yes| No| File type.| -| size | number | Yes| No| File size.| -| addedTime | number | Yes| No| Time when the file was scanned to the database.| -| modifiedTime | number | Yes| No| Time when the file was modified.| - -## DevInfo - -Defines the device type. - -**System capability**: SystemCapability.FileManagement.UserFileService - -### Attributes - -| Name| Type | Readable| Writable| Description | -| ------ | ------ | ---- | ---- | -------- | -| name | string | Yes | Yes | Device name.| diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index cc7d684666b28555597b406fddfc7b4c5cd7e130..aefc93a933ecdf42a0d270134d81f17c8a5788af 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -3,6 +3,7 @@ This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. > **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,11 +19,11 @@ Before using application event logging, you need to understand the requirements **Event Domain** -An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Name** -An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Type** @@ -32,7 +33,7 @@ An event type is an enumerated value of [EventType](#eventtype). An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: -- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_). +- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start or end with an underscore (\_). - The parameter value is a string, number, boolean, or array. - When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. @@ -404,12 +405,30 @@ Defines a subscription data holder for processing subscription events. **System capability**: SystemCapability.HiviewDFX.HiAppEvent +### constructor9+ + +constructor(watcherName: string); + +A constructor used to create a **holder** object. It is called automatically when a **Watcher** object is added. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +``` + ### setSize9+ setSize(size: number): void Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js @@ -425,6 +444,8 @@ takeNext(): [AppEventPackage](#appeventpackage9) Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 469fcae6f1c0f82f0894422b3e2a4416fabc7a60..53af9c42a3aa2d8cddf8d38290f7a29c30f8f9d6 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,6 +1,7 @@ # HiDebug -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. @@ -16,7 +17,7 @@ import hidebug from '@ohos.hidebug'; getNativeHeapSize(): bigint -Obtains the total size of the native heap memory. +Obtains the total size of the heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. @@ -26,84 +27,80 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. | Type | Description | | ------ | --------------------------- | -| bigint | Total size of the native heap memory, in kB.| +| bigint | Total size of the heap memory of this application, in kB.| **Example** - -```js -let nativeHeapSize = hidebug.getNativeHeapSize(); -``` + ```js + let nativeHeapSize = hidebug.getNativeHeapSize(); + ``` ## hidebug.getNativeHeapAllocatedSize getNativeHeapAllocatedSize(): bigint -Obtains the size of the allocated native heap memory. +Obtains the size of the allocated heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | --------------------------------- | -| bigint | Size of the allocated native heap memory, in kB.| +| bigint | Size of the allocated heap memory of this application, in kB.| **Example** - -```js -let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); -``` + ```js + let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); + ``` ## hidebug.getNativeHeapFreeSize getNativeHeapFreeSize(): bigint -Obtains the size of the free native heap memory. +Obtains the size of the free heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | ------------------------------- | -| bigint | Size of the free native heap memory, in kB.| +| bigint | Size of the free heap memory of this application, in kB.| **Example** - -```js -let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); -``` + ```js + let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); + ``` ## hidebug.getPss getPss(): bigint -Obtains the PSS of this process. +Obtains the size of the used physical memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | ------------------------- | -| bigint | PSS of the process, in kB.| +| bigint | Used physical memory of this process, in kB.| **Example** - -```js -let pss = hidebug.getPss(); -``` + ```js + let pss = hidebug.getPss(); + ``` ## hidebug.getSharedDirty @@ -114,18 +111,17 @@ Obtains the size of the shared dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the shared dirty memory of the process, in kB.| +| bigint | Size of the shared dirty memory of this process, in kB.| **Example** - -```js -let sharedDirty = hidebug.getSharedDirty(); -``` + ```js + let sharedDirty = hidebug.getSharedDirty(); + ``` ## hidebug.getPrivateDirty9+ @@ -135,11 +131,11 @@ Obtains the size of the private dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the private dirty memory of the process, in kB.| +| bigint | Size of the private dirty memory of this process, in kB.| **Example** @@ -157,18 +153,17 @@ For example, if the CPU usage is **50%**, **0.5** is returned. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| number | CPU usage of the process.| +| number | CPU usage of this process.| **Example** - -```js -let cpuUsage = hidebug.getCpuUsage(); -``` + ```js + let cpuUsage = hidebug.getCpuUsage(); + ``` ## hidebug.startProfiling @@ -195,6 +190,7 @@ hidebug.stopProfiling(); ``` + ## hidebug.stopProfiling stopProfiling() : void @@ -225,7 +221,7 @@ Exports data from the specified heap file. | Name | Type | Mandatory | Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the app based on the specified `filename`.| +| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.| **Example** @@ -250,7 +246,6 @@ This is a system API and cannot be called by third-party applications. | serviceid | number | Yes | ID of the system service. | **Return value** - | Type | Description | | ------ | -------------------------- | | string | Absolute path of the file that contains the service information to dump. | diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index 65952c0b23946b02582d74e5be9fbc5f8c33b42d..553ff5a9925a30f262acb49bb69cd4e95c7bd95b 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -2,7 +2,7 @@ Provides system event logging APIs for system HAP applications. -> **NOTE**
+> **NOTE** > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs. @@ -19,7 +19,7 @@ Enumerates event types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | FAULT | 1 | Error event.| | STATISTIC | 2 | Statistic event.| @@ -32,7 +32,7 @@ Defines a system event. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -50,7 +50,7 @@ Writes event information to the event file. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | | info | [SysEventInfo](#syseventinfo) | Yes| System event information.| | callback | AsyncCallback<void> | Yes| Callback used to process the received return value.
- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| @@ -91,13 +91,13 @@ Writes event information to the event file. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory| Description| +| Name | Type | Mandatory | Description| | --------- | ----------------------- | ---- | --------------- | | info | [SysEventInfo](#syseventinfo) | Yes | System event information.| **Return value** -| Type | Description | +| Type | Description | | ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| @@ -138,7 +138,7 @@ Enumerates matching rule types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | WHOLE_WORD | 1 | Whole word matching.| | PREFIX | 2 | Prefix matching.| @@ -150,7 +150,7 @@ Defines rules for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -163,7 +163,7 @@ Defines a watcher for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| | onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| @@ -181,7 +181,7 @@ Adds a watcher for event subscription. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| @@ -223,7 +223,7 @@ Removes a watcher used for event subscription. **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory | Description | | ------ | ------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| @@ -260,7 +260,7 @@ Defines arguments for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | beginTime | number | Yes| Start time (13-digit timestamp) for event query.| | endTime | number | Yes| End time (13-digit timestamp) for event query.| @@ -272,7 +272,7 @@ Defines rules for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | names | string[] | Yes| Array of event names.| @@ -283,7 +283,7 @@ Defines an event query instance. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| | onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| @@ -300,7 +300,7 @@ Queries system events. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 9e0e0bf5160d01596d0c6e0969c3cc783712f45a..294ed0fa79032d4e47e6c9c999183811d272acd3 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -358,7 +358,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques | Name | Type | Mandatory| Description | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | method | [RequestMethod](#requestmethod) | No | Request method. | -| extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.8+
- To pass in a string object, you first need to encode the object on your own.8+ | +| extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.8+ | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | @@ -432,7 +432,7 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| +| result | string \| Object \| ArrayBuffer6+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 2d66bc9c61a54f3bfa88d6e7f27aa93fabd49a2d..a886b6c643be1295bd49f0bf166d1e244d82f9af 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -12,1218 +12,2277 @@ The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by app ```js import huks from '@ohos.security.huks' ``` -## HuksErrorCode -Enumerates the error codes. +## HuksParam -**System capability**: SystemCapability.Security.Huks +Defines the **param** in the **properties** array of **options** used in the APIs. -| Name | Value | Description| -| -------------------------- | ----- | ---- | -| HUKS_SUCCESS | 0 |Success.| -| HUKS_FAILURE | -1 |Failure.| -| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| -| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| -| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| -| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| -| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| -| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| -| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| -| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| -| HUKS_ERROR_STORAGE_FAILURE | -10 |Storage failure.| -| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| -| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| -| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| -| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| -| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| -| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| -| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| -| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| -| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| -| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| -| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| -| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| -| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| -| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| -| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| -| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| -| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| -| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| -| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| -| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| -| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| -| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| -| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| -| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| -| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| -| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| -| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| -| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| -| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| -| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| -| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| -| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| -| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| -| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to check whether the ALG is obtained. | -| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to check whether the key size is obtained.| -| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to check whether padding is obtained.| -| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to check whether the purpose is obtained.| -| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to check whether digest is obtained.| -| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to check whether the mode is obtained.| -| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to check whether the nonce is obtained.| -| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to check whether the AAD is obtained.| -| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to check whether the initialization vector (IV) is obtained.| -| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to check whether the AE flag is obtained.| -| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to check whether the SALT is obtained.| -| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to check whether the iteration is obtained.| -| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| -| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| -| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding.| -| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid purpose.| -| HUKS_ERROR_INVALID_MODE | -116 |Invalid mode.| -| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest.| -| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| -| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| -| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| -| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| -| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| -| HUKS_ERROR_INVALID_SALT | -123 |Invalid SALT.| -| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration.| -| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| -| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| -| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| -| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| -| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| +**System capability**: SystemCapability.Security.Huks +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------ | +| tag | [HuksTag](#hukstag) | Yes | Tag. | +| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| -## HuksKeyPurpose +## HuksOptions -Enumerates the key purposes. +Defines the **options** used in the APIs. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------ | ---- | -------------------------------- | -| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt plaintext.| -| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| -| HUKS_KEY_PURPOSE_SIGN | 4 | Used to sign data. | -| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signed data. | -| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | -| HUKS_KEY_PURPOSE_WRAP | 32 | Used to wrap a key. | -| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used to unwrap a key. | -| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | -| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------- | ---- | ------------------------ | +| properties | Array\<[HuksParam](#huksparam)> | No | Properties used to hold the **HuksParam** array.| +| inData | Uint8Array | No | Input data. | -## HuksKeyDigest +## HuksSessionHandle9+ -Enumerates the digest algorithms. +Defines the HUKS handle structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_DIGEST_NONE | 0 | No digest algorithm| -| HUKS_DIGEST_MD5 | 1 | MD5| -| HUKS_DIGEST_SM39+ | 2 | SM3| -| HUKS_DIGEST_SHA1 | 10 | SHA1| -| HUKS_DIGEST_SHA224 | 11 | SHA-224| -| HUKS_DIGEST_SHA256 | 12 | SHA-256| -| HUKS_DIGEST_SHA384 | 13 | SHA-384| -| HUKS_DIGEST_SHA512 | 14 | SHA-512| +| Name | Type | Mandatory| Description | +| --------- | ---------- | ---- | ---------------------------------------------------- | +| handle | number | Yes | Value of the handle. | +| challenge | Uint8Array | No | Challenge obtained after the [init](#huksinit) operation.| -## HuksKeyPadding +## HuksReturnResult9+ -Enumerates the padding algorithms. +Defines the **HuksResult** structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_PADDING_NONE | 0 | No padding algorithm| -| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| -| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| -| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5| -| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS) #5| -| HUKS_PADDING_PKCS7 | 5 | PKCS #7| -## HuksCipherMode -Enumerates the cipher modes. +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------- | ---- | ---------------- | +| outData | Uint8Array | No | Output data. | +| properties | Array\<[HuksParam](#huksparam)> | No | Property information. | +| certChains | Array\ | No | Certificate chain information.| -**System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------- | ---- | --------------------- | -| HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode| -| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| -| HUKS_MODE_CTR | 3 | Counter (CTR) mode| -| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| -| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| -| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| +## huks.generateKeyItem9+ -## HuksKeySize +generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key sizes. +Generates a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------- | ---- | ------------------------------------------ | -| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | -| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | -| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | -| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | -| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | -| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | -| HUKS_ECC_KEY_SIZE_224 | 224 | ECC key of 224 bits | -| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | -| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | -| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | -| HUKS_AES_KEY_SIZE_128 | 128 | AES key of 128 bits | -| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | -| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | -| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | -| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| -| HUKS_DH_KEY_SIZE_2048 | 2048 | DH key of 2048 bits | -| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | -| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | -| HUKS_SM2_KEY_SIZE_2569+ | 256 | SM2 key of 256 bits | -| HUKS_SM4_KEY_SIZE_1289+ | 128 | SM4 key of 128 bits | +**Parameters** -## HuksKeyAlg +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the key algorithms. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------- | ---- | --------------------- | -| HUKS_ALG_RSA | 1 | RSA | -| HUKS_ALG_ECC | 2 | ECC | -| HUKS_ALG_DSA | 3 | DSA | -| HUKS_ALG_AES | 20 | AES | -| HUKS_ALG_HMAC | 50 | HMAC | -| HUKS_ALG_HKDF | 51 | HKDF | -| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | -| HUKS_ALG_ECDH | 100 | ECDH | -| HUKS_ALG_X25519 | 101 | X25519 | -| HUKS_ALG_ED25519 | 102 | ED25519| -| HUKS_ALG_DH | 103 | DH | -| HUKS_ALG_SM29+ | 150 | SM2 | -| HUKS_ALG_SM39+ | 151 | SM3 | -| HUKS_ALG_SM49+ | 152 | SM4 | +## huks.generateKeyItem9+ -## HuksKeyGenerateType +generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the key generation types. +Generates a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------------ | ---- | ---------------- | -| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| -| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| -| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| +**Parameters** -## HuksKeyFlag +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| -Enumerates the key generation modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------------- | ---- | ------------------------------------ | -| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using an API. | -| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using an API. | -| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using a key agreement API.| -| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is derived by using an API.| +## huks.deleteKeyItem9+ -## HuksKeyStorageType +deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key storage modes. +Deletes a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ----------------------- | ---- | ------------------------------ | -| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | -| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| +**Parameters** -## HuksSendType +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the tag transfer modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: deleteKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------- | ---- | ----------------- | -| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| -| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| +## huks.deleteKeyItem9+ -## HuksUnwrapSuite9+ +deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the algorithm suites used when a wrapped key is imported. +Deletes a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------------------- | ---- | ----------------------------------------------------- | -| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| -| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | - -## HuksImportKeyType9+ +**Parameters** -Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| ------------------------- | ---- | ------------------------------ | -| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | -| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | -| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| - -## HuksUserAuthType9+ - -Enumerates the user authentication types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------- | -| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | -| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| -| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| - -## HuksAuthAccessType9+ - -Enumerates the access control types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| --------------------------------------- | ---- | ------------------------------------------------ | -| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key is invalid after the password is cleared. | -| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key is invalid after a new biometric feature is added.| - -## HuksChallengeType9+ - -Enumerates the types of the challenges generated when a key is used. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| -| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| -| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| - -## HuksChallengePosition9+ - -Enumerates the positions of the 8-byte valid value in a custom challenge generated. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31 indicate the valid challenge of the key.| - -## HuksSecureSignType9+ - -Defines the signature type of the key generated or imported. - -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: deleteKeyItem key success`); + }) + .catch(error => { + console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------------ | ---- | ------------------------------------------------------------ | -| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used to sign data, the data will be added with the authentication information and then be signed.| +## huks.getSdkVersion -## HuksTagType +getSdkVersion(options: HuksOptions) : string -Enumerates the tag data types. +Obtains the SDK version of the current system. **System capability**: SystemCapability.Security.Huks +**Parameters** -| Name | Value | Description | -| --------------------- | ------- | --------------------------------------- | -| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | -| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | -| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| -| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | -| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | -| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | +| Name | Type | Mandatory| Description | +| ------- | ---------- | ---- | ------------------------- | +| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| -## HuksTag +**Return value** -Enumerates the tags used to invoke parameters. +| Type | Description | +| ------ | ------------- | +| string | SDK version obtained.| -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | -| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | -| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | -| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | -| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | -| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | -| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | -| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | -| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | -| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | -| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | -| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | -| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | -| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | -| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | -| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | -| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | -| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | -| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | -| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | -| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | -| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | -| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | -| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | -| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | -| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite used when a wrapped key is imported. | -| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | -| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | -| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | -| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | -| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | -| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | -| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | -| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set the authentication type to **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, or their combination.| -| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | -| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | -| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| -| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| -| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| -| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| -| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | -| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | -| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. | -| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | -| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. | -| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. | -| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. | -| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Device manufacturer. | -| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | -| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. | -| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | -| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | -| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| -| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | -| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | -| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | -| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | -| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | -| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | -| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | -| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | -| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | -| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | -| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | -| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | -| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | -| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | -| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | -| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | -| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | -| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | -| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | -| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | -| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | -| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | -| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | +```js +/* Set options to emptyOptions. */ +let emptyOptions = { + properties: [] +}; +let result = huks.getSdkVersion(emptyOptions); +``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Generates a key. This API uses an asynchronous callback to return the result. +Imports a key in plaintext. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code defined in **HuksResult** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Generate an RSA key of 512 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_OAEP + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var options = { - properties: properties +let options = { + properties: properties, + inData: plainTextSize32 }; -huks.generateKey(keyAlias, options, function (err, data){}); +try { + huks.importKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: importKeyItem success`); + } + }); +} catch (error) { + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions) : Promise\ +importKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Generates a key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| - -**Return value** - -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Example** ```js -/* Generate an ECC key of 256 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; -var options = { - properties: properties +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var result = huks.generateKey(keyAlias, options); +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +try { + huks.importKeyItem(keyAlias, huksoptions) + .then ((data) => { + console.info(`promise: importKeyItem success`); + }) + .catch(error => { + console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Deletes a key. This API uses an asynchronous callback to return the result. +Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated. | -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + huks.attestKeyItem(aliasString, options, function (error, data) { + if (error) { + console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: attestKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions) : Promise\ +attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Deletes a key. This API uses a promise to return the result. +Obtains the certificate used to verify a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ----------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated.| -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | --------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -var result = huks.deleteKey(keyAlias, emptyOptions); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + await huks.generateKeyItem(alias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + await huks.attestKeyItem(aliasString, options) + .then ((data) => { + console.info(`promise: attestKeyItem success`); + }) + .catch(error => { + console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.getSdkVersion +## huks.importWrappedKeyItem9+ -getSdkVersion(options: HuksOptions) : string +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the SDK version of the current system. +Imports a wrapped key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------- | ---- | ------------------------- | -| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| - -**Return value** - -| Type | Description | -| ------ | ------------- | -| string | SDK version obtained.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var emptyOptions = { - properties: [] +import huks from '@ohos.security.huks'; + +let exportWrappingKey; +let alias1 = "importAlias"; +let alias2 = "wrappingKeyAlias"; + +async function TestGenFunc(alias, options) { + try { + await genKey(alias, options) + .then((data) => { + console.info(`callback: generateKeyItem success`); + }) + .catch(error => { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function genKey(alias, options) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestExportFunc(alias, options) { + try { + await exportKey(alias, options) + .then ((data) => { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportWrappingKey = data.outData; + }) + .catch(error => { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function exportKey(alias, options) : Promise { + return new Promise((resolve, reject) => { + try { + huks.exportKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await importWrappedKey(alias, wrappingAlias, options) + .then ((data) => { + console.info(`callback: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function importWrappedKey(alias, wrappingAlias, options) { + return new Promise((resolve, reject) => { + try { + huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedKeyFunc( + alias, + wrappingAlias, + genOptions, + importOptions +) { + await TestGenFunc(wrappingAlias, genOptions); + await TestExportFunc(wrappingAlias, genOptions); + + /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. + * For example, import **keyA**. + * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. + * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. + * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. + * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**. + * 5. Generate the **importOptions.inData** field in the following format: + * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + + * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + + * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + + * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + + * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc + */ + let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); + importOptions.inData = inputKey; + await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +} + +function makeGenerateOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, + value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, + }; + let options = { + properties: properties + }; + return options; }; -var result = huks.getSdkVersion(emptyOptions); + +function makeImportOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, + value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING + }; + let options = { + properties: properties + }; + return options; +}; + +function huksImportWrappedKey() { + let genOptions = makeGenerateOptions(); + let importOptions = makeImportOptions(); + TestImportWrappedKeyFunc( + alias1, + alias2, + genOptions, + importOptions + ); +} ``` -## huks.importKey +## huks.importWrappedKeyItem9+ -importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses an asynchronous callback to return the result. +Imports a wrapped key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| **Example** ```js -/* Import an AES key of 256 bits. */ -var plainTextSize32 = makeRandomArr(32); -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); +/* The process is similar as if a callback is used, except the following:*/ +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await huks.importWrappedKeyItem(alias, wrappingAlias, options) + .then ((data) => { + console.info(`promise: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } - return arr; -}; -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var options = { - properties: properties, - inData: plainTextSize32 +} +``` + +## huks.exportKeyItem9+ + +exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Exports a key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -huks.importKey(keyAlias, options, function (err, data){}); +try { + huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.importKey +## huks.exportKeyItem9+ -importKey(keyAlias: string, options: HuksOptions) : Promise\ +exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses a promise to return the result. +Exports a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | ------------------------------------------------------------ | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js -/* Import an AES key of 128 bits. */ -var plainTextSize32 = makeRandomArr(32); - -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); - } - return arr; -}; - -/* Step 1 Generate a key. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var huksoptions = { - properties: properties, - inData: plainTextSize32 +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -var result = huks.importKey(keyAlias, huksoptions); +try { + huks.exportKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.attestkey9+ +## huks.getKeyItemProperties9+ -attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. +Obtains key properties. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.getKeyItemProperties9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\ - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; +Obtains key properties. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options, function (err, data) { - printLog(`key attest result : ${JSON.stringify(data)}`); - }); +## huks.isKeyItemExist9+ + +isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Checks whether a key exists. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------- | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`); + } else { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } ``` -## huks.attestkey9+ +## huks.isKeyItemExist9+ -attestKey(keyAlias: string, options: HuksOptions) : Promise\ +isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\ -Obtains the certificate used to verify a key. This API uses a promise to return the result. +Checks whether a key exists. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.initSession9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; -} +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options) - .then((data) => { - console.log(`test attestKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test attestKey information: ' + JSON.stringify(err)); - }); -} -``` +**System capability**: SystemCapability.Security.Huks -## huks.importWrappedKey9+ +**Parameters** -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | +| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes | Callback invoked to return the key operation handle.| -Imports a wrapped key. This API uses an asynchronous callback to return the result. + +## huks.initSession9+ + +initSession(keyAlias: string, options: HuksOptions) : Promise\ + +Initializes the data for a key operation. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | Yes | Token of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Updates the key operation data by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ----------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | No | Token for the **Finish** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + + +## huks.abortSession9+ + +abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Aborts the use of the key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** ```js -var exportWrappingKey; -var alias1 = "importAlias"; -var alias2 = "wrappingKeyAlias"; - -async function TestGenFunc(alias, options) { - await genKey(alias, options) - .then((data) => { - console.log(`test genKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test genKey err information: ' + JSON.stringify(err)); - }); +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function genKey(alias, options) { - return new Promise((resolve, reject) => { - huks.generateKey(alias, options, function (err, data) { - console.log(`test genKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test genKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) +}; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } + + try { + await huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestExportFunc(alias, options) { - await exportKey(alias, options) - .then((data) => { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test exportKey err information: ' + JSON.stringify(err)); - }); +async function huksInit() { + console.log('enter huksInit'); + try { + huks.initSession(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + } + }); + } catch (error) { + console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function exportKey(alias, options) { - return new Promise((resolve, reject) => { - huks.exportKey(alias, options, function (err, data) { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test exportKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - exportWrappingKey = data.outData; - resolve(data); - } - }); - }); +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + huks.updateSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - await importWrappedKey(alias, wrappingAlias, options) - .then((data) => { - console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test importWrappedKey err information: ' + JSON.stringify(err)); - }); +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + huks.finishSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function importWrappedKey(alias, wrappingAlias, options) { - return new Promise((resolve, reject) => { - huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) { - console.log(`importWrappedKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('importWrappedKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +async function huksAbort() { + console.log('enter huksAbort'); + try { + huks.abortSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: abortSession success`); + } + }); + } catch (error) { + console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } +``` -async function TestImportWrappedKeyFunc( - alias, - wrappingAlias, - genOptions, - importOptions -) { - await TestGenFunc(wrappingAlias, genOptions); - await TestExportFunc(wrappingAlias, genOptions); +## huks.abortSession9+ - /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. - * For example, import **keyA**. - * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. - * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. - * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. - * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, ** aad2**, ciphertext **kek_enc**, and encrypted **tag2**. - * 5. Generate the **importOptions.inData** field in the following format: - * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + - * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + - * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + - * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + - * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc - */ - var inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); - importOptions.inData = inputKey; - await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +abortSession(handle: number, options: HuksOptions) : Promise\; + +Aborts the use of the key. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function makeGenerateOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - var options = { - properties: properties - }; - return options; +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) }; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } -function makeImportOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, - value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING - }; - var options = { - properties: properties - }; - return options; + try { + await huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksInit() { + console.log('enter huksInit'); + try { + await huks.initSession(keyAlias, options) + .then ((data) => { + console.info(`promise: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + }) + .catch(error => { + console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + await huks.updateSession(handle, options) + .then ((data) => { + console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + await huks.finishSession(handle, options) + .then ((data) => { + console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksAbort() { + console.log('enter huksAbort'); + try { + await huks.abortSession(keyAlias, options) + .then ((data) => { + console.info(`promise: abortSession success`); + }) + .catch(error => { + console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} +``` + + +## HuksExceptionErrCode9+ + +Enumerates the error codes. + +For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md). + +**System capability**: SystemCapability.Security.Huks + +| Name | Description | Error Code | +| ---------------------------------------------- | --------------------------- | -------- | +| HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | 201 | +| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | 401 | +| HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | 801 | +| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | 12000001 | +| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | 12000002 | +| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | 12000003 | +| HUKS_ERR_CODE_FILE_OPERATION_FAIL | The file operation failed. | 12000004 | +| HUKS_ERR_CODE_COMMUNICATION_FAIL | The communication failed. | 12000005 | +| HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | 12000006 | +| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 | +| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| 12000008 | +| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| 12000009 | +| HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | 12000010 | +| HUKS_ERR_CODE_ITEM_NOT_EXIST | The target object does not exist. | 12000011 | +| HUKS_ERR_CODE_EXTERNAL_ERROR | An external error occurs. | 12000012 | +| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The credential does not exist. | 12000013 | +| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | The memory is insufficient. | 12000014 | +| HUKS_ERR_CODE_CALL_SERVICE_FAILED | Failed to call other system services. | 12000015 | + +## HuksKeyPurpose + +Enumerates the key purposes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------- | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| +| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing. | +| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature. | +| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | +| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export. | +| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import. | +| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | +| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | + +## HuksKeyDigest + +Enumerates the digest algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_DIGEST_NONE | 0 | No digest algorithm| +| HUKS_DIGEST_MD5 | 1 | MD5| +| HUKS_DIGEST_SM39+ | 2 | SM3| +| HUKS_DIGEST_SHA1 | 10 | SHA-1| +| HUKS_DIGEST_SHA224 | 11 | SHA-224| +| HUKS_DIGEST_SHA256 | 12 | SHA-256| +| HUKS_DIGEST_SHA384 | 13 | SHA-384| +| HUKS_DIGEST_SHA512 | 14 | SHA-512| + +## HuksKeyPadding + +Enumerates the padding algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_PADDING_NONE | 0 | No padding algorithm| +| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| +| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| +| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5| +| HUKS_PADDING_PKCS5 | 4 | PKCS #5| +| HUKS_PADDING_PKCS7 | 5 | PKCS #7| + +## HuksCipherMode + +Enumerates the cipher modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------- | ---- | --------------------- | +| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode| +| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| +| HUKS_MODE_CTR | 3 | Counter (CTR) mode| +| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| +| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| +| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| + +## HuksKeySize + +Enumerates the key sizes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------- | ---- | ------------------------------------------ | +| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | +| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | +| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | +| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | +| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | +| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | +| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits | +| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | +| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | +| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | +| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | +| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | +| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | +| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | +| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| +| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits | +| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | +| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | +| HUKS_SM2_KEY_SIZE_2569+ | 256 | ShangMi2 (SM2) key of 256 bits | +| HUKS_SM4_KEY_SIZE_1289+ | 128 | ShangMi4 (SM4) key of 128 bits | + +## HuksKeyAlg + +Enumerates the key algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | --------------------- | +| HUKS_ALG_RSA | 1 | RSA | +| HUKS_ALG_ECC | 2 | ECC | +| HUKS_ALG_DSA | 3 | DSA | +| HUKS_ALG_AES | 20 | AES | +| HUKS_ALG_HMAC | 50 | HMAC | +| HUKS_ALG_HKDF | 51 | HKDF | +| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | +| HUKS_ALG_ECDH | 100 | ECDH | +| HUKS_ALG_X25519 | 101 | X25519 | +| HUKS_ALG_ED25519 | 102 | ED25519| +| HUKS_ALG_DH | 103 | DH | +| HUKS_ALG_SM29+ | 150 | SM2 | +| HUKS_ALG_SM39+ | 151 | SM3 | +| HUKS_ALG_SM49+ | 152 | SM4 | + +## HuksKeyGenerateType + +Enumerates the key generation types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------- | +| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| +| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| +| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| + +## HuksKeyFlag + +Enumerates the key generation modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------- | ---- | ------------------------------------ | +| HUKS_KEY_FLAG_IMPORT_KEY | 1 | Import a key using an API. | +| HUKS_KEY_FLAG_GENERATE_KEY | 2 | Generate a key by using an API. | +| HUKS_KEY_FLAG_AGREE_KEY | 3 | Generate a key by using a key agreement API.| +| HUKS_KEY_FLAG_DERIVE_KEY | 4 | Derive a key by using an API.| + +## HuksKeyStorageType + +Enumerates the key storage modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ----------------------- | ---- | ------------------------------ | +| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | +| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| + +## HuksSendType + +Enumerates the tag transfer modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------- | ---- | ----------------- | +| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| +| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| + +## HuksUnwrapSuite9+ + +Enumerates the algorithm suites required for encrypted imports. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------------------- | ---- | ----------------------------------------------------- | +| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| +| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | + +## HuksImportKeyType9+ + +Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------ | +| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | +| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | +| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| + +## HuksUserAuthType9+ + +Enumerates the user authentication types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------- | +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | +| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| +| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| + +## HuksAuthAccessType9+ + +Enumerates the access control types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------------------------- | ---- | ------------------------------------------------ | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key becomes invalid after the password is cleared. | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key becomes invalid after a new biometric feature is added.| + +## HuksChallengeType9+ + +Enumerates the types of the challenges generated when a key is used. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| +| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| +| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| + +## HuksChallengePosition9+ + +Enumerates the positions of the 8-byte valid value in a custom challenge generated. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7.| +| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15.| +| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23.| +| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31.| + +## HuksSecureSignType9+ + +Defines the signature type of the key generated or imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ------------------------------------------------------------ | +| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.| + +## HuksTagType + +Enumerates the tag data types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | +| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | +| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| +| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | +| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | +| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | + +## HuksTag + +Enumerates the tags used to invoke parameters. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | +| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | +| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. | +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | +| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | +| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports. | +| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | +| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | +| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | +| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | +| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | +| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | +| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT | +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | +| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| +| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| +| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| +| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | +| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device. | +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device. | +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device. | +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device. | +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device. | +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | +| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | +| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | +| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | +| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | +| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | +| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | +| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | +| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | +| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | +| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | +| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | +| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | +| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | +| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | +| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | +| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | +| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | +| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | +| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | +| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | +| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Generates a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. For details about other results, see HuksResult.| + +**Example** + +```js +/* Generate an RSA key of 512 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_OAEP +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +huks.generateKey(keyAlias, options, function (err, data){}); +``` + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions) : Promise\ + +Generates a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +let result = huks.generateKey(keyAlias, options); +``` + + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Deletes a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +``` + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions) : Promise\ + +Deletes a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +let result = huks.deleteKey(keyAlias, emptyOptions); +``` + + +## huks.importKey(deprecated) + +importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Imports a key in plaintext. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------------------------------- | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; - -function huksImportWrappedKey() { - var genOptions = makeGenerateOptions(); - var importOptions = makeImportOptions(); - TestImportWrappedKeyFunc( - alias1, - alias2, - genOptions, - importOptions - ); -} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let options = { + properties: properties, + inData: plainTextSize32 +}; +huks.importKey(keyAlias, options, function (err, data){}); ``` -## huks.importWrappedKey9+ +## huks.importKey(deprecated) -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ +importKey(keyAlias: string, options: HuksOptions) : Promise\ -Imports a wrapped key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9-1). **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------------- | ---- | --------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Return value** | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* The process is similar as if a callback is used, except the following:*/ -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - var result = await huks.importWrappedKey(alias, wrappingAlias, options); - if (result.errorCode === 0) { - console.log('test importWrappedKey success'); - } else { - console.log('test importWrappedKey fail'); - } -} +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +let result = huks.importKey(keyAlias, huksoptions); ``` -## huks.exportKey + +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Exports a key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1232,25 +2291,27 @@ Exports a key. This API uses an asynchronous callback to return the result. | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.exportKey(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.exportKey +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions) : Promise\ Exports a key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1264,25 +2325,28 @@ Exports a key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.exportKey(keyAlias, emptyOptions); +let result = huks.exportKey(keyAlias, emptyOptions); ``` -## huks.getKeyProperties + +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Obtains key properties. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1291,25 +2355,27 @@ Obtains key properties. This API uses an asynchronous callback to return the res | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.getKeyProperties +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ Obtains key properties. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1323,25 +2389,28 @@ Obtains key properties. This API uses a promise to return the result. | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned. **properties** returns the parameters required for generating the key.| +| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.getKeyProperties(keyAlias, emptyOptions); +let result = huks.getKeyProperties(keyAlias, emptyOptions); ``` -## huks.isKeyExist + +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Checks whether a key exists. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1350,25 +2419,27 @@ Checks whether a key exists. This API uses an asynchronous callback to return th | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the key to check.| | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| -| callback | AsyncCallback\ | Yes | Callback used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.isKeyExist +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ Checks whether a key exists. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1382,26 +2453,26 @@ Checks whether a key exists. This API uses a promise to return the result. | Type | Description | | ----------------- | --------------------------------------- | -| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.isKeyExist(keyAlias, emptyOptions); +let result = huks.isKeyExist(keyAlias, emptyOptions); ``` - - -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Initializes the data for a key operation. This API uses an asynchronous callback to return the result. +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1411,14 +2482,16 @@ Initializes the data for a key operation. This API uses an asynchronous callback | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the initialization operation.| +| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback invoked to return the key operation handle.| -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions) : Promise\ -Initializes the data for a key operation. This API uses a promise to return the result. +Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1428,52 +2501,21 @@ Initializes the data for a key operation. This API uses a promise to return the | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the initialization operation.| - - -## huks.update(deprecated) - -update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void - -Updates the key operation data by segment. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.update9+](#huksupdate9-1). - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.| -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| ## huks.update(deprecated) -update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ - -Updates the key operation data by segment. This API uses a promise to return the result. - -> **NOTE**
This API is discarded since API version 9. You are advised to use [huks.update9+](#huksupdate9-2). - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - -## huks.update9+ - update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9). **System capability**: SystemCapability.Security.Huks @@ -1483,14 +2525,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| +## huks.update(deprecated) -## huks.update9+ +update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void -update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-1). **System capability**: SystemCapability.Security.Huks @@ -1499,15 +2542,17 @@ Updates the key operation by segment. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| token | Uint8Array | Yes | Token of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| -## huks.update9+ +## huks.update(deprecated) update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ -Updates the key operation by segment. This API uses a promise to return the result. +Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-2). **System capability**: SystemCapability.Security.Huks @@ -1516,15 +2561,23 @@ Updates the key operation by segment. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ----------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | token | Uint8Array | No | Token of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -## huks.finish +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| + + +## huks.finish(deprecated) finish(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9). **System capability**: SystemCapability.Security.Huks @@ -1534,14 +2587,16 @@ Completes the key operation and releases resources. This API uses an asynchronou | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| -## huks.finish +## huks.finish(deprecated) finish(handle: number, options: HuksOptions) : Promise\ -Completes the key operation and releases resources. This API uses a promise to return the result. +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1551,49 +2606,22 @@ Completes the key operation and releases resources. This API uses a promise to r | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void - -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | Yes | Token for the **Finish** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - - -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ - -Completes the key operation and releases resources. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | ----------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | No | Token for the **Finish** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions, callback: AsyncCallback\) : void Aborts the use of the key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1602,7 +2630,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| **Example** @@ -1612,27 +2640,14 @@ Aborts the use of the key. This API uses an asynchronous callback to return the * * The following uses the callback of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; async function generateKey() { properties[0] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, @@ -1657,11 +2672,11 @@ async function generateKey() { huks.generateKey(keyalias, options); } function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } async function huksInit() { @@ -1708,112 +2723,16 @@ async function huksAbort() { }); console.log(resultMessage); } - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('Tocallback') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - routePage() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions) : Promise\; Aborts the use of the key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1822,7 +2741,12 @@ Aborts the use of the key. This API uses a promise to return the result. | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| **Example** @@ -1832,34 +2756,20 @@ Aborts the use of the key. This API uses a promise to return the result. * * The following uses the promise of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} - -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } @@ -1890,7 +2800,7 @@ async function huksInit() { return new Promise((resolve, reject) => { huks.init(keyalias, options, async function (err, data) { if (data.errorCode === 0) { - resultMessage = "Initialization successful!" + resultMessage = "init success!" handle = data.handle; } else { resultMessage = "init fail errorCode: " + data.errorCode @@ -1935,128 +2845,10 @@ function huksAbort() { }); }); } -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('to Promise') - .fontSize(20) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - router.back() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## HuksParam - -Defines the **param** in the **properties** array of **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------------- | ---- | ------------ | -| tag | [HuksTag](#hukstag) | Yes | Tag. | -| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| - -## HuksOptions - -Defines the **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name | Type | Mandatory| Description | -| ---------- | ----------------- | ---- | ------------------------ | -| properties | Array\<[HuksParam](#huksparam)> | No | Array used to hold **HuksParam**.| -| inData | Uint8Array | No | Input data. | -## HuksHandle +## HuksHandle(deprecated) Defines the HUKS handle structure. @@ -2069,7 +2861,7 @@ Defines the HUKS handle structure. | token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| -## HuksResult +## HuksResult(deprecated) Defines the **HuksResult** structure. @@ -2083,3 +2875,87 @@ Defines the **HuksResult** structure. | outData | Uint8Array | No | Output data. | | properties | Array\<[HuksParam](#huksparam)> | No | Property information. | | certChains | Array\ | No | Certificate chain information.| + + +## HuksErrorCode(deprecated) + +Enumerates the error codes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description| +| -------------------------- | ----- | ---- | +| HUKS_SUCCESS | 0 |Success.| +| HUKS_FAILURE | -1 |Failure.| +| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| +| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| +| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| +| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| +| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| +| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| +| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| +| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| +| HUKS_ERROR_STORAGE_FAILURE | -10 |Insufficient storage space.| +| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| +| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| +| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| +| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| +| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| +| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| +| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| +| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| +| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| +| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| +| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| +| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| +| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| +| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| +| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| +| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| +| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| +| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| +| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| +| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| +| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| +| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| +| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| +| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| +| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| +| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| +| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| +| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| +| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| +| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| +| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| +| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| +| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| +| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. | +| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.| +| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.| +| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to obtain the key purpose.| +| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to obtain the digest algorithm.| +| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to obtain the cipher mode.| +| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to obtain the nonce.| +| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to obtain the AAD.| +| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to obtain the initialization vector (IV).| +| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to obtain the AE flag.| +| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to obtain the salt value.| +| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to obtain the number of iterations.| +| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| +| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| +| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding algorithm.| +| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid key purpose.| +| HUKS_ERROR_INVALID_MODE | -116 |Invalid cipher mode.| +| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest algorithm.| +| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| +| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| +| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| +| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| +| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| +| HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.| +| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.| +| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| +| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| +| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| +| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| +| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 866a5833b69feb01da451f2464fbdd7915f06172..6b7463a11b96f468bd275b0fd0fd841fe690713c 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -40,9 +40,11 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper const color = new ArrayBuffer(96); let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts) - .then((pixelmap) => { - }) +image.createPixelMap(color, opts).then((pixelmap) => { + console.log('Succeeded in creating pixelmap.'); +}).catch(error => { + console.log('Failed to create pixelmap.'); +}) ``` ## image.createPixelMap8+ @@ -115,7 +117,7 @@ const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer).then(() => { console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. }).catch(error => { - console.log('Failed to read image pixel data.'); // Called if no condition is met. + console.log('Failed to read image pixel data.'); // Called if no condition is met. }) ``` @@ -392,7 +394,6 @@ Obtains pixel map information of this image. This API uses a promise to return t const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } image.createPixelMap(color, opts).then(pixelmap => { - globalpixelmap = pixelmap; if (pixelmap == undefined) { console.error("Failed to obtain the image pixel map information."); } @@ -428,7 +429,6 @@ const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (err, pixelmap) => { if (pixelmap == undefined) { - globalpixelmap = pixelmap; console.error("Failed to obtain the image pixel map information."); } pixelmap.getImageInfo((err, imageInfo) => { @@ -559,9 +559,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return **Example** ```js -async function () { - var rate = 0.5; - await pixelmap.opacity(rate); +async function Demo() { + await pixelmap.opacity(0.5); } ``` @@ -582,9 +581,9 @@ Creates a **PixelMap** object that contains only the alpha channel information. **Example** ```js -async function () { - await pixelmap.createAlphaPixelmap(); -}) +async function Demo() { + await pixelmap.createAlphaPixelmap(); +} ``` ### createAlphaPixelmap9+ @@ -632,7 +631,7 @@ Scales this image based on the input width and height. This API uses an asynchro **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -661,7 +660,7 @@ Scales this image based on the input width and height. This API uses a promise t **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -685,7 +684,7 @@ Translates this image based on the input coordinates. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -714,7 +713,7 @@ Translates this image based on the input coordinates. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -737,7 +736,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -765,7 +764,7 @@ Rotates this image based on the input angle. This API uses a promise to return t **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -789,7 +788,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -818,7 +817,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -841,7 +840,7 @@ Crops this image based on the input size. This API uses an asynchronous callback **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -869,7 +868,7 @@ Crops this image based on the input size. This API uses a promise to return the **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -891,15 +890,10 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }).catch(error => { - console.log('Failed to release pixelmap object.'); - }) +pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); +}).catch(error => { + console.log('Failed to release pixelmap object.'); }) ``` @@ -920,13 +914,8 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }) +pixelmap.release(() => { + console.log('Succeeded in releasing pixelmap object.'); }) ``` @@ -1345,11 +1334,10 @@ Modifies the value of a property in this image. This API uses a promise to retur **Example** ```js -imageSourceApi.modifyImageProperty("ImageWidth", "120") - .then(() => { - const w = imageSourceApi.getImageProperty("ImageWidth") - console.info('w', w); - }) +imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => { + const w = imageSourceApi.getImageProperty("ImageWidth") + console.info('w', w); +}) ``` ### modifyImageProperty9+ @@ -1401,9 +1389,9 @@ Updates incremental data. This API uses a promise to return the result. ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => { - console.info('Succeeded in updating data.'); - }) +imageSourceApi.updateData(array, false, 0, 10).then(data => { + console.info('Succeeded in updating data.'); +}) ``` @@ -1429,11 +1417,11 @@ Updates incremental data. This API uses an asynchronous callback to return the r ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> { - if(data !== undefined){ - console.info('Succeeded in updating data.'); - } - }) +imageSourceApi.updateData(array, false, 0, 10,(error,data )=> { + if(data !== undefined){ + console.info('Succeeded in updating data.'); + } +}) ``` ### createPixelMap7+ @@ -1617,6 +1605,7 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` @@ -1645,6 +1634,7 @@ Packs an image. This API uses a promise to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 } imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { @@ -1673,10 +1663,14 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts, data => { - console.log('Succeeded in packing the image.'); +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts, data => { + console.log('Succeeded in packing the image.'); + }) }) ``` @@ -1704,14 +1698,18 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts) - .then( data => { - console.log('Succeeded in packing the image.'); - }).catch(error => { - console.log('Failed to pack the image..'); - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts) + .then( data => { + console.log('Succeeded in packing the image.'); + }).catch(error => { + console.log('Failed to pack the image..'); + }) +}) ``` ### release @@ -1764,7 +1762,7 @@ imagePackerApi.release().then(()=>{ createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver -Create an **ImageReceiver** instance by specifying the image width, height, format, and capacity. +Creates an **ImageReceiver** instance by specifying the image width, height, format, and capacity. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver @@ -1774,7 +1772,7 @@ Create an **ImageReceiver** instance by specifying the image width, height, form | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format. | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1955,7 +1953,7 @@ receiver.readNextImage().then(img => { }) ``` -### on('imageArrival')9+ +### on9+ on(type: 'imageArrival', callback: AsyncCallback\): void @@ -2020,6 +2018,228 @@ receiver.release().then(() => { }) ``` +## image.createImageCreator9+ + +createImageCreator(width: number, height: number, format: number, capacity: number): ImageCreator + +Creates an **ImageCreator** instance by specifying the image width, height, format, and capacity. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| width | number | Yes | Default image width. | +| height | number | Yes | Default image height. | +| format | number | Yes | Image format, for example, YCBCR_422_SP or JPEG. | +| capacity | number | Yes | Maximum number of images that can be accessed at the same time.| + +**Return value** + +| Type | Description | +| ------------------------------ | --------------------------------------- | +| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| + +**Example** + +```js +var creator = image.createImageCreator(8192, 8, 4, 8); +``` + +## ImageCreator9+ + +Requests an image native data area, and provides APIs for applications to compile native image data. +Before calling any APIs in **ImageCreator**, you must create an **ImageCreator** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +| Name | Type | Readable| Writable| Description | +| -------- | ---------------------------- | ---- | ---- | ------------------ | +| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.| +| format | [ImageFormat](#imageformat9) | Yes | No | Image format. | + +### dequeueImage9+ + +dequeueImage(callback: AsyncCallback\): void + +Obtains an image buffer from the idle queue and writes image data into it. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage((err, img) => { + if (err) { + console.info('dequeueImage succeeded.'); + } + console.info('dequeueImage failed.')); +}); +``` + +### dequeueImage9+ + +dequeueImage(): Promise\ + +Obtains an image buffer from the idle queue and writes image data into it. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| --------------- | ------------- | +| Promise\ | Promise used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage().then(img => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.log('dequeueImage failed: ' + error); +}) +``` + +### queueImage9+ + +queueImage(interface: Image, callback: AsyncCallback\): void + +Places the drawn image in the dirty queue. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| interface | Image | Yes | Drawn image.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img, (err) => { + if (err) { + console.info('dequeueImage failed: ' + err); + } + console.info('dequeueImage succeeded'); +}) +``` + +### queueImage9+ + +queueImage(interface: Image): Promise\ + +Places the drawn image in the dirty queue. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------| ---- | ------------------- | +| interface | Image | Yes | Drawn image.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img).then(() => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.info('dequeueImage failed: ' + error); +}) +``` + +### on9+ + +on(type: 'imageRelease', callback: AsyncCallback\): void + +Listens for image release events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| type | string | Yes | Type of event, which is **'imageRelease'**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.on('imageRelease', (err) => { + if (err) { + console.info('on faild' + err); + } + console.info('on succeeded'); +}) +``` + +### release9+ + +release(callback: AsyncCallback\): void + +Releases this **ImageCreator** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release((err) => { + if (err) { + console.info('release failed: ' + err); + } + console.info('release succeeded'); +}); +``` +### release9+ + +release(): Promise\ + +Releases this **ImageCreator** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release().then(() => { + console.info('release succeeded'); +}).catch(error => { + console.info('release failed'); +}) +``` + ## Image9+ Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An **Image** instance is returned when [readNextImage](#readnextimage9) and [readLatestImage](#readlatestimage9) are called. @@ -2147,7 +2367,7 @@ Describes area information in an image. | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | pixels | ArrayBuffer | Yes | No | Pixels of the image. | | offset | number | Yes | No | Offset for data reading. | -| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | +| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| ## ImageInfo @@ -2159,6 +2379,7 @@ Describes image information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ---------- | | size | [Size](#size) | Yes | Yes | Image size.| +| density9+ | number | Yes | Yes | Pixel density, in ppi.| ## Size @@ -2181,8 +2402,13 @@ Enumerates the pixel formats of images. | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | -| RGBA_8888 | 3 | RGBA_8888. | -| BGRA_88889+ | 4 | BGRA_8888. | +| RGBA_8888 | 3 | RGBA_8888.| +| BGRA_88889+ | 4 | BGRA_8888.| +| RGB_8889+ | 5 | RGB_888. | +| ALPHA_89+ | 6 | ALPHA_8. | +| RGBA_F169+ | 7 | RGBA_F16. | +| NV219+ | 8 | NV21. | +| NV129+ | 9 | NV12. | ## AlphaType9+ @@ -2194,8 +2420,8 @@ Enumerates the alpha types of images. | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | +| PREMUL | 2 | Premultiplied alpha. | +| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | ## ScaleMode9+ @@ -2250,6 +2476,7 @@ Defines image decoding options. | desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| | index | number | Yes | Yes | Index of the image to decode. | +| fitDensity9+ | number | Yes | Yes | Image pixel density, in ppi. | ## Region7+ @@ -2260,7 +2487,7 @@ Describes region information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ------------ | | size | [Size](#size) | Yes | Yes | Region size. | -| x | number | Yes | Yes | X coordinate of the region.| +| x | number | Yes | Yes | X coordinate to translate.| | y | number | Yes | Yes | Y coordinate of the region.| ## PackingOption @@ -2271,8 +2498,9 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image.
Currently, the JPEG and WebP formats are supported. | +| format | string | Yes | Yes | Format of the packed image.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| +| bufferSize9+ | number | Yes | Yes | Buffer size, which is used to set the image size. The default value is 10 MB.| ## GetImagePropertyOptions7+ @@ -2299,8 +2527,14 @@ Describes the exchangeable image file format (EXIF) information of an image. | IMAGE_WIDTH | "ImageWidth" | Image width. | | GPS_LATITUDE | "GPSLatitude" | Image latitude. | | GPS_LONGITUDE | "GPSLongitude" | Image longitude. | -| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | -| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | +| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Shooting time, for example, 2022:09:06 15:48:00. | +| EXPOSURE_TIME9+ | "ExposureTime" | Exposure time, for example, 1/33 sec.| +| SCENE_TYPE9+ | "SceneType" | Shooting scene mode, for example, portrait, scenery, motion, and night sight. | +| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. | +| F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. | + ## ImageFormat9+ diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 3c908fabdc24cccc6f5949c9d5add8da88a08d01..79cdf3ac5627984eba2f03e7eb37b9cc7137de4a 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -64,7 +64,7 @@ Creates a Locale object. | Name | Type | Mandatory | Description | | ------- | ------------- | ---- | ---------------------------- | | locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -| options | LocaleOptions | No | Options for creating the **Locale** object. | +| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | **Example** ``` @@ -181,7 +181,7 @@ Creates a **DateTimeOptions** object for the specified locale. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [DateTimeOptions](#datetimeoptions) | No | Options for creating a **DateTimeFormat** object. | +| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | **Example** ``` @@ -265,7 +265,7 @@ Obtains the formatting options for **DateTimeFormat** object. | Type | Description | | ----------------------------------- | ----------------------------- | -| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| +| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| **Example** ``` @@ -332,7 +332,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [NumberOptions](#numberoptions) | No | Options for creating a **NumberFormat** object. | +| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | **Example** ``` @@ -380,7 +380,7 @@ Obtains the options of the **NumberFormat** object. | Type | Description | | ------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| +| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| **Example** @@ -449,7 +449,7 @@ Creates a Collator object. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [CollatorOptions](#collatoroptions) | No | Options for creating a **Collator** object. | +| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | **Example** ``` @@ -497,9 +497,10 @@ Returns properties reflecting the locale and collation options of a **Collator** | Type | Description | | ----------------------------------- | ----------------- | -| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| +| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| **Example** + ``` var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); @@ -552,7 +553,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [PluralRulesOptions](#pluralrulesoptions) | No | Options for creating a **PluralRules** object. | +| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | **Example** ``` @@ -634,7 +635,7 @@ Creates a **RelativeTimeFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No | Options for creating a **RelativeTimeFormat** object. | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | **Example** ``` @@ -710,7 +711,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. | Type | Description | | ---------------------------------------- | --------------------------------- | -| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| +| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 50057062701f1ddbe0b058dc79e957c1a47e63a3..189042b1f1df1727423c65c0a226b11ae473db2a 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -42,18 +42,18 @@ Registers a listener to observe the mission status. **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); - - ``` +``` ## missionManager.unregisterMissionListener @@ -77,21 +77,22 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid, (error) => { - console.log("unregisterMissionListener"); + console.log("unregisterMissionListener"); }) - ``` +``` ## missionManager.unregisterMissionListener @@ -120,21 +121,22 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} - }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); - - missionManager.unregisterMissionListener(listenerid).catch(function (err){ - console.log(err); - }); - ``` +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + }; + console.log("registerMissionListener") + var listenerid = missionManager.registerMissionListener(listener); + + missionManager.unregisterMissionListener(listenerid).catch(function (err) { + console.log(err); + }); +``` ## missionManager.getMissionInfo diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 1d272e9f03c4956e141456324b1eb1f05293cea8..da2443a7c87c363ae79085a9b0dfeda4f7f5af99 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -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,6 +115,9 @@ 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 @@ -160,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 @@ -792,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 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-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-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index d133b1b37776187ac1120f42ead17e98273f0db4..b397ba221d3d570e3b5eca2f551ecee228bdfc35 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -37,4 +37,4 @@ export default class MainAbility extends Ability { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 26d35ffeca4fe9c60ae46d8a8794fe46cb3d1748..ec920f58cab6825ce1dd286f42d1eb24e759f10b 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -384,6 +384,27 @@ promise.then(data => { }); ``` +## radio.isNrSupported7+ + +isNrSupported\(\): boolean + +Checks whether the current device supports 5G \(NR\). + +**System capability**: SystemCapability.Telephony.CoreService + +**Return value** + +| Type | Description | +| ------- | -------------------------------- | +| boolean | - **true**: The current device supports 5G \(NR\).
- **false**: The current device does not support 5G \(NR\).| + +**Example** + +```js +let result = radio.isNrSupported(); +console.log("Result: "+ result); +``` + ## radio.isNrSupported8+ diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 5b9107af6a142f762171272278e3ea543bb93b81..7df95d23175b36a0e4aefa65ea0b04c1862a2c94 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -22,720 +22,888 @@ A sensor is a device to detect events or changes in an environment and send mess import sensor from '@ohos.sensor'; ``` -## sensor.on +## sensor.on9+ -### ACCELEROMETER +### ACCELEROMETER9+ -on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void +on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void -Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the acceleration sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### LINEAR_ACCELERATIONdeprecated +```js +try { + sensor.on(sensor.SensorId.ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void +### ACCELEROMETER_UNCALIBRATED9+ -Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>,options?: Options): void -This API is deprecated since API version 9. You are advised to use **Sensor.on.LINEAR_ACCELEROMETER9+** instead. +Subscribes to data of the uncalibrated acceleration sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### LINEAR_ACCELEROMETER9+ +```js +try { + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,callback:Callback<LinearAccelerometerResponse>, options?: Options): void +### AMBIENT_LIGHT9+ -Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the ambient light sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### ACCELEROMETER_UNCALIBRATED +```js +try { + sensor.on(sensor.SensorId.AMBIENT_LIGHT,function(data){ + console.info('Illumination: ' + data.intensity); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void +### AMBIENT_TEMPERATURE9+ -Subscribes to data changes of the uncalibrated acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the ambient temperature sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` -### GRAVITY +```js +try { + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE,function(data){ + console.info('Temperature: ' + data.temperature); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### BAROMETER9+ -on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void +on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, options?: Options): void -Subscribes to data changes of the gravity sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the barometer sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ + +```js +try { + sensor.on(sensor.SensorId.BAROMETER,function(data){ + console.info('Atmospheric pressure: ' + data.pressure); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### GRAVITY9+ + +on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: Options): void + +Subscribes to data of the gravity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.on(sensor.SensorId.GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GYROSCOPE +### GYROSCOPE9+ -on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void +on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options?: Options): void -Subscribes to data changes of the gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the gyroscope sensor. -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + +```js +try { + sensor.on(sensor.SensorId.GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GYROSCOPE_UNCALIBRATED +### GYROSCOPE_UNCALIBRATED9+ -on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void +on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>, + options?: Options): void -Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the uncalibrated gyroscope sensor. -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE -**System capability**: SystemCapability.Sensors.Sensor +**System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ + +```js +try { + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### SIGNIFICANT_MOTION +### HALL9+ -on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void +on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Options): void -Subscribes to data changes of the significant motion sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the Hall effect sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 10000000} - ); - ``` -### PEDOMETER_DETECTION +```js +try { + sensor.on(sensor.SensorId.HALL,function(data){ + console.info('Status: ' + data.status); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void +### HEART_RATE9+ -Subscribes to data changes of the pedometer detection sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the heart rate sensor. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | Callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 10000000} - ); - ``` -### PEDOMETER +```js +try { + sensor.on(sensor.SensorId.HEART_RATE,function(data){ + console.info('Heart rate: ' + data.heartRate); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void +### HUMIDITY9+ -Subscribes to data changes of the pedometer sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the humidity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ - console.info('Steps: ' + data.steps); - }, - {interval: 10000000} - ); - ``` -### AMBIENT_TEMPERATURE +```js +try { + sensor.on(sensor.SensorId.HUMIDITY,function(data){ + console.info('Humidity: ' + data.humidity); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void +### LINEAR_ACCELERATION9+ -Subscribes to data changes of the ambient temperature sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>, + options?: Options): void + +Subscribes to data of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ - console.info('Temperature: ' + data.temperature); - }, - {interval: 10000000} - ); - ``` -### MAGNETIC_FIELD +```js +try { + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### MAGNETIC_FIELD9+ -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void +on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void -Subscribes to data changes of the magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ + +```js +try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### MAGNETIC_FIELD_UNCALIBRATED +### MAGNETIC_FIELD_UNCALIBRATED9+ -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void +on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void -Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the uncalibrated magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ + +```js +try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### PROXIMITY +### ORIENTATION9+ -on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void +on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,options?: Options): void -Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the orientation sensor. **System capability**: SystemCapability.Sensors.Sensor +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ - console.info('Distance: ' + data.distance); - }, - {interval: 10000000} - ); - ``` -### HUMIDITY - -on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void +```js +try { + sensor.on(sensor.SensorId.ORIENTATION,function(data){ + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -Subscribes to data changes of the humidity sensor. If this API is called multiple times for the same application, the last call takes effect. +### PEDOMETER9+ -**System capability**: SystemCapability.Sensors.Sensor +on(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +Subscribes to data of the pedometer sensor. -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ - console.info('Humidity: ' + data.humidity); - }, - {interval: 10000000} - ); - ``` +**Required permissions**: ohos.permission.ACTIVITY_MOTION -### BAROMETER +**System capability**: SystemCapability.Sensors.Sensor -on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void +**Error code** -Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**System capability**: SystemCapability.Sensors.Sensor +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ - console.info('Atmospheric pressure: ' + data.pressure); - }, - {interval: 10000000} - ); - ``` -### HALL +```js +try { + sensor.on(sensor.SensorId.PEDOMETER,function(data){ + console.info('Steps: ' + data.steps); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void +### PEDOMETER_DETECTION9+ -Subscribes to data changes of the Hall effect sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, + options?: Options): void -**System capability**: SystemCapability.Sensors.Sensor +Subscribe to data of the pedometer detection sensor. -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +**Required permissions**: ohos.permission.ACTIVITY_MOTION -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ - console.info('Status: ' + data.status); - }, - {interval: 10000000} - ); - ``` +**System capability**: SystemCapability.Sensors.Sensor -### AMBIENT_LIGHT +**Parameters** -on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -Subscribes to data changes of the ambient light sensor. If this API is called multiple times for the same application, the last call takes effect. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ - console.info(' Illumination: ' + data.intensity); - }, - {interval: 10000000} - ); - ``` -### ORIENTATION +```js +try { + sensor.on(sensor.SensorId.PEDOMETER_DETECTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### PROXIMITY9+ -on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void +on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, options?: Options): void -Subscribes to data changes of the orientation sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the proximity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - }, - {interval: 10000000} - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -### HEART_RATEdeprecated +**Error code** -on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the heart rate sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.on(sensor.SensorId.PROXIMITY,function(data){ + console.info('Distance: ' + data.distance); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -This API is deprecated since API version 9. You are advised to use **sensor.on.HEART_BEAT_RATE9+** instead. +### ROTATION_VECTOR9+ -**Required permissions**: ohos.permission.READ_HEALTH_DATA +on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>, + options?: Options): void + +Subscribes to data of the rotation vector sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ - console.info("Heart rate: " + data.heartRate); -}, - {interval: 10000000} -); +try { + sensor.on(sensor.SensorId.ROTATION_VECTOR,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -### HEART_BEAT_RATE9+ - -on(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback: Callback<HeartRateResponse>, options?: Options): void +### SIGNIFICANT_MOTION9+ -Subscribes to only one data change of the heart rate sensor. +on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, + options?: Options): void -**Required permissions**: ohos.permission.READ_HEALTH_DATA +Subscribes to data of the significant motion sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE,function(data){ - console.info("Heart rate: " + data.heartRate); -}, - {interval: 10000000} -); +try { + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -### ROTATION_VECTOR +### WEAR_DETECTION9+ -on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void +on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>, + options?: Options): void -Subscribes to data changes of the rotation vector sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the wear detection sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | - -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }, - {interval: 10000000} - ); - ``` -### WEAR_DETECTION +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void - -Subscribes to data changes of the wear detection sensor. If this API is called multiple times for the same application, the last call takes effect. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ + +```js +try { + sensor.on(sensor.SensorId.WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -## sensor.once +## sensor.once9+ -### ACCELEROMETER +### ACCELEROMETER9+ -once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void +once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>): void -Subscribes to only one data change of the acceleration sensor. +Subscribes to data of the acceleration sensor once. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` - -### LINEAR_ACCELERATIONdeprecated - -once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void - -Subscribes to only one data change of the linear acceleration sensor. -This API is deprecated since API version 9. You are advised to use **sensor.once.LINEAR_ACCELEROMETER9+** instead. +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { + +```js +try { + sensor.once(sensor.SensorId.ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); } ); - ``` +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### LINEAR_ACCELEROMETER9+ +### ACCELEROMETER_UNCALIBRATED9+ -once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,callback:Callback<LinearAccelerometerResponse>): void +once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>): void -Subscribes to only one data change of the linear acceleration sensor. +Subscribes to data of the uncalibrated acceleration sensor once. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### ACCELEROMETER_UNCALIBRATED - -once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void - -Subscribes to only one data change of the uncalibrated acceleration sensor. +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { + +```js +try { + sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -744,1649 +912,2107 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. console.info('Z-coordinate bias: ' + data.biasZ); } ); - ``` +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GRAVITY +### AMBIENT_LIGHT9+ -once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void +once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): void -Subscribes to only one data change of the gravity sensor. +Subscribes to data of the ambient light sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### GYROSCOPE +```js +try { + sensor.once(sensor.SensorId.AMBIENT_LIGHT, function(data) { + console.info('Illumination: ' + data.intensity); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void +### AMBIENT_TEMPERATURE9+ -Subscribes to only one data change of the gyroscope sensor. +once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the ambient temperature sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### GYROSCOPE_UNCALIBRATED +```js +try { + sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function(data) { + console.info('Temperature: ' + data.temperature); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void +### BAROMETER9+ -Subscribes to only one data change of the uncalibrated gyroscope sensor. +once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the barometer sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| -### SIGNIFICANT_MOTION +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the significant motion sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` - -### PEDOMETER_DETECTION +```js +try { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void +### GRAVITY9+ -Subscribes to only one data change of the pedometer detection sensor. +once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the gravity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` - -### PEDOMETER +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void +**Error code** -Subscribes to only one data change of the pedometer sensor. +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Required permissions**: ohos.permission.ACTIVITY_MOTION +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +```js +try { + sensor.once(sensor.SensorId.GRAVITY, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { - console.info('Steps: ' + data.steps); - } - ); - ``` +### GYROSCOPE9+ -### AMBIENT_TEMPERATURE +once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void +Subscribes to data of the gyroscope sensor once. -Subscribes to only one data change of the ambient temperature sensor. +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { - console.info('Temperature: ' + data.temperature); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -### MAGNETIC_FIELD +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the magnetic field sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +```js +try { + sensor.once(sensor.SensorId.GYROSCOPE, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` +### GYROSCOPE_UNCALIBRATED9+ -### MAGNETIC_FIELD_UNCALIBRATED +once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void +Subscribes to data of the uncalibrated gyroscope sensor once. -Subscribes to only one data change of the uncalibrated magnetic field sensor. +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` - -### PROXIMITY -once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -Subscribes to only one data change of the proximity sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { - console.info('Distance: ' + data.distance); - } - ); - ``` -### HUMIDITY +```js +try { + sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### HALL9+ -once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void +once(type: SensorId.HALL, callback: Callback<HallResponse>): void -Subscribes to only one data change of the humidity sensor. +Subscribes to data of the Hall effect sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { - console.info('Humidity: ' + data.humidity); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -### BAROMETER +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the barometer sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +```js +try { + sensor.once(sensor.SensorId.HALL, function(data) { + console.info('Status: ' + data.status); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - ); - ``` +### HEART_RATE9+ -### HALL +once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void +Subscribes to data of the heart rate sensor once. -Subscribes to only one data change of the Hall effect sensor. +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { - console.info('Status: ' + data.status); - } - ); - ``` - -### AMBIENT_LIGHT -once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| -Subscribes to only one data change of the ambient light sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { - console.info(' Illumination: ' + data.intensity); - } - ); - ``` -### ORIENTATION +```js +try { + sensor.once(sensor.SensorId.HEART_BEAT_RATE, function(data) { + console.info('Heart rate: ' + data.heartRate); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void +### HUMIDITY9+ -Subscribes to only one data change of the orientation sensor. +once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void + +Subscribes to data of the humidity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - ); - ``` - -### ROTATION_VECTOR -once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -Subscribes to only one data change of the rotation vector sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - ); - ``` -### HEART_RATEdeprecated +```js +try { + sensor.once(sensor.SensorId.HUMIDITY, function(data) { + console.info('Humidity: ' + data.humidity); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void +### LINEAR_ACCELERATION9+ -Subscribes to only one data change of the heart rate sensor. +once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>): void -This API is deprecated since API version 9. You are advised to use **sensor.once.HEART_BEAT_RATE9+** instead. +Subscribes to data of the linear acceleration sensor once. -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { - console.info("Heart rate: " + data.heartRate); - } - ); - ``` -### HEART_BEAT_RATE9+ +```js +try { + sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback: Callback<HeartRateResponse>): void +### MAGNETIC_FIELD9+ -Subscribes to only one data change of the heart rate sensor. +once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void -**Required permissions**: ohos.permission.READ_HEALTH_DATA +Subscribes to data of the magnetic field sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, function(data) { - console.info("Heart rate: " + data.heartRate); - } - ); - ``` -### WEAR_DETECTION +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void - -Subscribes to only one data change of the wear detection sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { - console.info("Wear status: "+ data.value); - } - ); - ``` - -## sensor.off -### ACCELEROMETER +```js +try { + sensor.once(sensor.SensorId.MAGNETIC_FIELD, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void +### MAGNETIC_FIELD_UNCALIBRATED9+ -Unsubscribes from sensor data changes. +once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the uncalibrated magnetic field sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('x-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); ``` -### ACCELEROMETER_UNCALIBRATED - -off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void +### ORIENTATION9+ -Unsubscribes from sensor data changes. +once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the orientation sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); +try { + sensor.once(sensor.SensorId.ORIENTATION, function(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); ``` -### AMBIENT_LIGHT +### PEDOMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void +once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the pedometer sensor once. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -**Example** +**Error code** -```js -function callback(data) { - console.info(' Illumination: ' + data.intensity); -} -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); -``` - -### AMBIENT_TEMPERATURE - -off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Unsubscribes from sensor data changes. - -**System capability**: SystemCapability.Sensors.Sensor - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Temperature: ' + data.temperature); +try { + sensor.once(sensor.SensorId.PEDOMETER, function(data) { + console.info('Steps: ' + data.steps); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off( sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); ``` -### AMBIENT_TEMPERATURE +### PEDOMETER_DETECTION9+ -off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void +once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>): void -Unsubscribes from sensor data changes. +Subscribe to data of the pedometer detection sensor once. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**.| -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Atmospheric pressure: ' + data.pressure); +try { + sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); ``` -### GRAVITY +### PROXIMITY9+ -off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void +once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the proximity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.PROXIMITY, function(data) { + console.info('Distance: ' + data.distance); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); ``` -### GYROSCOPE - -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void +### ROTATION_VECTOR9+ -Unsubscribes from sensor data changes. +once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the rotation vector sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**.| -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.ROTATION_VECTOR, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ``` -### GYROSCOPE_UNCALIBRATED - -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void +### SIGNIFICANT_MOTION9+ -Unsubscribes from sensor data changes. +once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the significant motion sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); ``` -### HALL +### WEAR_DETECTION9+ -off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void +once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the wear detection sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Status: ' + data.status); +try { + sensor.once(sensor.SensorId.WEAR_DETECTION, function(data) { + console.info("Wear status: "+ data.value); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); ``` -### HEART_RATEdeprecated +## sensor.off9+ -off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void +### ACCELEROMETER9+ -Unsubscribes from sensor data changes. +off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void -This API is deprecated since API version 9. You are advised to use **sensor.off.HEART_BEAT_RATE9+** instead. +Unsubscribes from data of the acceleration sensor. -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**.| -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| **Example** ```js -function callback(data) { - console.info("Heart rate: " + data.heartRate); +try { + function callback(data) { + console.info('x-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.ACCELEROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback); ``` -### HEART_BEAT_RATE9+ +### ACCELEROMETER_UNCALIBRATED9+ -off(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback?: Callback<HeartRateResponse>): void +off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the uncalibrated acceleration sensor. -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**.| -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| **Example** ```js -function callback(data) { - console.info("Heart rate: " + data.heartRate); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback); ``` -### HUMIDITY +### AMBIENT_LIGHT9+ -off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void +off(type: SensorId.AMBIENT_LIGHT, callback?: Callback<LightResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the ambient light sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| **Example** ```js -function callback(data) { - console.info('Humidity: ' + data.humidity); +try { + function callback(data) { + console.info('Illumination: ' + data.intensity); + } + sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); ``` -### LINEAR_ACCELERATIONdeprecated - -off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void - -Unsubscribes from sensor data changes. +### AMBIENT_TEMPERATURE9+ -This API is deprecated since API version 9. You are advised to use **sensor.off.LINEAR_ACCELEROMETER9+** instead. +off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Unsubscribes from data of the ambient temperature sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('Temperature: ' + data.temperature); + } + sensor.off( sensor.SensorId.AMBIENT_TEMPERATURE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); ``` -### LINEAR_ACCELEROMETER9+ - -off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerometerResponse>): void +### BAROMETER9+ -Unsubscribes from sensor data changes. +off(type: SensorId.BAROMETER, callback?: Callback<BarometerResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Unsubscribes from data of the barometer sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + sensor.off(sensor.SensorId.BAROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback); ``` -### MAGNETIC_FIELD +### GRAVITY9+ - off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void +off(type: SensorId.GRAVITY, callback?: Callback<GravityResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the gravity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| -| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off( sensor.SensorId.GRAVITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); ``` -### MAGNETIC_FIELD_UNCALIBRATED +### GYROSCOPE9+ - off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void +off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the gyroscope sensor. + +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.GYROSCOPE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); ``` -### ORIENTATION +### GYROSCOPE_UNCALIBRATED9+ - off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void +off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void -Unsubscribes from sensor data changes. + Unsubscribes from data of the uncalibrated gyroscope sensor. + +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**.| -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GYROSCOPE_UNCALIBRATED**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| **Example** ```js -function callback(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); ``` -### PEDOMETER - -off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void +### HALL9+ -Unsubscribes from sensor data changes. +off(type: SensorId.HALL, callback?: Callback<HallResponse>): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Unsubscribes from data of the Hall effect sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| **Example** ```js -function callback(data) { - console.info('Steps: ' + data.steps); +try { + function callback(data) { + console.info('Status: ' + data.status); + } + sensor.off(sensor.SensorId.HALL, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); ``` -### PEDOMETER_DETECTION +### HEART_RATE9+ -off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void +off(type: SensorId.HEART_RATE, callback?: Callback<HeartRateResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the heart rate sensor. -**Required permissions**: ohos.permission.ACTIVITY_MOTION +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| **Example** ```js -function callback(data) { - console.info('Scalar data: ' + data.scalar); +try { + function callback(data) { + console.info("Heart rate: " + data.heartRate); + } + sensor.off(sensor.SensorId.HEART_RATE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); ``` -### PROXIMITY +### HUMIDITY9+ -off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void +off(type: SensorId.HUMIDITY, callback?: Callback<HumidityResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the humidity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**.| -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| **Example** ```js -function callback(data) { - console.info('Distance: ' + data.distance); +try { + function callback(data) { + console.info('Humidity: ' + data.humidity); + } + sensor.off(sensor.SensorId.HUMIDITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); ``` -### ROTATION_VECTOR +### LINEAR_ACCELEROMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void +off(type: SensorId.LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerometerResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); ``` -### SIGNIFICANT_MOTION +### MAGNETIC_FIELD9+ -off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void +off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| **Example** ```js -function callback(data) { - console.info('Scalar data: ' + data.scalar); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); ``` -### WEAR_DETECTION +### MAGNETIC_FIELD_UNCALIBRATED9+ -off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void +off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the uncalibrated magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| **Example** ```js -function accCallback(data) { - console.info('Wear status: ' + data.value); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); ``` -## sensor.transformCoordinateSystem +### ORIENTATION9+ -transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void +off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): void -Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. +Unsubscribes from data of the orientation sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | ----------- | -| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| **Example** ```js -sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { - if (err) { - console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Operation successed. Data obtained: " + data); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); +try { + function callback(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); } - }) + sensor.off(sensor.SensorId.ORIENTATION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.transformCoordinateSystem -transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> +### PEDOMETER9+ -Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. +off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): void -**System capability**: SystemCapability.Sensors.Sensor +Unsubscribes from data of the pedometer sensor. -**Parameters** +**Required permissions**: ohos.permission.ACTIVITY_MOTION -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | -------- | -| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| +**System capability**: SystemCapability.Sensors.Sensor -**Return value** +**Parameters** -| Type | Description | -| ---------------------------------- | ----------- | -| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| **Example** ```js -const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); - promise.then((data) => { - console.info("Operation successed."); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }).catch((err) => { - console.info("Operation failed"); -}) +try { + function callback(data) { + console.info('Steps: ' + data.steps); + } + sensor.off(sensor.SensorId.PEDOMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.getGeomagneticField +### PEDOMETER_DETECTION9+ -getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void +off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void -Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. +Unsubscribes from data of the pedometer detection sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | -| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | -| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| -| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| **Example** + ```js -sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { - if (err) { - console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); - return; +try { + function callback(data) { + console.info('Scalar data: ' + data.scalar); } - console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); -}); + sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.getGeomagneticField -getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> +### PROXIMITY9+ -Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. +off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): void + +Unsubscribes from data of the proximity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | ----------------------------------- | ---- | ----------------- | -| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | -| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| -**Return value** -| Type | Description | -| ---------------------------------------- | ------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| **Example** - ```js - const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); - promise.then((data) => { - console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); - }).catch((reason) => { - console.info('Operation failed.'); - }) - ``` -## sensor.getAltitude +```js +try { + function callback(data) { + console.info('Distance: ' + data.distance); + } + sensor.off(sensor.SensorId.PROXIMITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### ROTATION_VECTOR9+ -getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void +off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void -Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. +Unsubscribes from data of the rotation vector sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | ---- | -------------------- | -| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | -| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| -| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| **Example** - ```js - sensor.getAltitude(0, 200, function(err, data) { - if (err) { - console.error( - "Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Successed to get getAltitude interface get data: " + data); - }); - ``` +```js +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + sensor.off(sensor.SensorId.ROTATION_VECTOR, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -## sensor.getAltitude +### SIGNIFICANT_MOTION9+ -getAltitude(seaPressure: number, currentPressure: number): Promise<number> +off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void -Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. +Unsubscribes from data of the significant motion sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | ------ | ---- | -------------------- | -| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | -| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -**Return value** +**Example** -| Type | Description | -| --------------------- | ------------------ | -| Promise<number> | Promise used to return the altitude, in meters.| +```js +try { + function callback(data) { + console.info('Scalar data: ' + data.scalar); + } + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** +### WEAR_DETECTION9+ - ```js - const promise = sensor.getAltitude(0, 200); - promise.then((data) => { - console.info(' sensor_getAltitude_Promise success', data); - }).catch((err) => { - console.error("Operation failed"); - }) - ``` +off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void +Unsubscribes from data of the wear detection sensor. -## sensor.getGeomagneticDip +**System capability**: SystemCapability.Sensors.Sensor -getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void +**Parameters** -Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + +**Example** + +```js +try { + function accCallback(data) { + console.info('Wear status: ' + data.value); + } + sensor.off(sensor.SensorId.WEAR_DETECTION, accCallback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +## sensor.getGeomagneticInfo9+ + +getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void + +Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------------- | --------------------------- | ---- | -------------- | -| inclinationMatrix | Array<number> | Yes | Inclination matrix. | -| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getGeomagneticInfo](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + - err.message); - return; - } - console.info("Successed to get getGeomagneticDip interface get data: " + data); - }) - ``` +```js +try { + sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000, function(data) { + console.info('sensor_getGeomagneticInfo_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + }); +} catch (err) { + console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getGeomagneticDip +## sensor.getGeomagneticInfo9+ -getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> +getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> -Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. +Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------------- | ------------------- | ---- | ------- | -| inclinationMatrix | Array<number> | Yes | Inclination matrix.| +| Name | Type | Mandatory| Description | +| --------------- | ----------------------------------- | ---- | ---------------------------------- | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| **Return value** -| Type | Description | -| --------------------- | -------------- | -| Promise<number> | Promise used to return the magnetic dip, in radians.| +| Type | Description | +| ---------------------------------------------------------- | -------------- | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getGeomagneticInfo](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); +```js +try { + const promise = sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000); promise.then((data) => { - console.info('getGeomagneticDip_promise successed', data); - }).catch((err) => { - console.error("Operation failed"); + console.info('sensor_getGeomagneticInfo_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + }).catch((reason) => { + console.info('Operation failed.'); }) - ``` +} catch (err) { + console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor. getAngleModify +## sensor.getDeviceAltitude9+ -getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void +getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void -Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------------- | ---------------------------------------- | ---- | ------------------ | -| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | -| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| +| Name | Type | Mandatory| Description | +| --------------- | --------------------------- | ---- | ------------------------------------- | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| +| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | -**Example** +**Error code** - ```js - sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { - if (err) { - console.error('Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) - ``` +For details about the following error codes, see [Error Codes of sensor.getDeviceAltitude](../errorcodes/errorcode-sensor.md). +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -## sensor. getAngleModify +**Example** -getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> +```js +try { + sensor.getDeviceAltitude(0, 200, function(data) { + console.info('Successed to get getDeviceAltitude interface get data: ' + data); + }); +} catch (err) { + console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -Obtains the angle change between two rotation matrices. This API uses a promise to return the result. +## sensor.getDeviceAltitude9+ + +getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<number> + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------------- | ------------------- | ---- | --------- | -| currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| -| preRotationMatrix | Array<number> | Yes | Rotation matrix. | +| Name | Type | Mandatory| Description | +| --------------- | ------ | ---- | ------------------------------------- | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | -| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| +| Type | Description | +| --------------------- | ------------------------------------ | +| Promise<number> | Promise used to return the altitude, in meters.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getDeviceAltitude](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); +```js +try { + const promise = sensor.getDeviceAltitude (0, 200); promise.then((data) => { - console.info('getAngleModifiy_promise success'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((reason) => { - console.info("promise::catch", reason); + console.info('sensor_getDeviceAltitude_Promise success', data); + }).catch((err) => { + console.error("Operation failed"); }) - ``` - +} catch (err) { + console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getInclination9+ -createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void +getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void -Converts a rotation vector into a rotation matrix. This API uses an asynchronous callback to return the result. +Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| +| Name | Type | Mandatory| Description | +| ----------------- | --------------------------- | ---- | ---------------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | +| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getInclination](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } +```js +try { + sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { + console.info('Successed to get getInclination interface get data: ' + data); }) - ``` - +} catch (err) { + console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getInclination9+ -createRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> + getInclination(inclinationMatrix: Array<number>): Promise<number> -Converts a rotation vector into a rotation matrix. This API uses a promise to return the result. + Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory| Description | +| ----------------- | ------------------- | ---- | -------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix.| **Return value** -| Type | Description | -| ---------------------------------- | ------- | -| Promise<Array<number>> | Promise used to return the rotation matrix.| +| Type | Description | +| --------------------- | ---------------------------- | +| Promise<number> | Promise used to return the magnetic dip, in radians.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getInclination](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); +```js +try { + const promise = sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info('createRotationMatrix_promise success'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((reason) => { - console.info("promise::catch", reason); - }) - ``` - + console.info('getInclination_promise successed', data); + }).catch((err) => { + console.error("Operation failed"); + }) +} catch (err) { + console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createQuaternion +## sensor.getAngleVariation9+ -createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, + callback: AsyncCallback): void -Converts a rotation vector into a quaternion. This API uses an asynchronous callback to return the result. +Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | +| Name | Type | Mandatory| Description | +| --------------------- | ---------------------------------------- | ---- | --------------------------------- | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getAngleVariation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } +```js +try { + sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(data) { for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } }) - ``` - +} catch (err) { + console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createQuaternion +## sensor.getAngleVariation9+ -createQuaternion(rotationVector: Array<number>): Promise<Array<number>> +getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise -Converts a rotation vector into a quaternion. This API uses a promise to return the result. +Obtains the angle change between two rotation matrices. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory| Description | +| --------------------- | ------------------- | ---- | ------------------ | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<Array<number>> | Promise used to return the quaternion.| +| Type | Description | +| ---------------------------------- | --------------------------------- | +| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getAngleVariation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); +```js +try { + const promise = sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); promise.then((data) => { - console.info('createQuaternion_promise successed'); for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); + console.info('data[' + i + ']: ' + data[i]); } - }).catch((err) => { - console.info('promise failed'); + }).catch((reason) => { + console.info('promise::catch ', reason); }) - ``` - +} catch (err) { + console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getDirection +## sensor.getRotationMatrix9+ -getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void +getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback): void -Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. +Obtains the rotation matrix from a rotation vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------------------ | -| rotationMatrix | Array<number> | Yes | Rotation matrix. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_callback" + data[i]); +```js +try { + sensor.getRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(data) { + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } }) - ``` - +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getDirection +## sensor.getRotationMatrix9+ -getDirection(rotationMatrix: Array<number>): Promise<Array<number>> +getRotationMatrix(rotationVector: Array<number>): Promise -Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. +Obtains the rotation matrix from a rotation vector. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationMatrix | Array<number> | Yes | Rotation matrix.| +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | -| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| +| Type | Description | +| ---------------------------------- | -------------- | +| Promise<Array<number>> | Promise used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); +```js +try { + const promise = sensor.getRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { - console.info('sensor_getAltitude_Promise success', data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_promise" + data[i]); + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } - }).catch((err) => { - console.info('promise failed'); + }).catch((reason) => { + console.info('promise::catch ', reason); }) - ``` +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` +## sensor.transformRotationMatrix9+ -## sensor.createRotationMatrix +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions, + callback: AsyncCallback): void -createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ----------------------------------------- | ---- | ---------------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.transformRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(data) { + for (var i=0; i < data.length; i++) { + console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + } + }) +} catch (err) { + console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.transformRotationMatrix9+ + +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ----------------------------------------- | ---- | ---------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------------- | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.transformRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + const promise = sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + promise.then((data) => { + for (var i=0; i < data.length; i++) { + console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + } + }).catch((err) => { + console.info("Operation failed"); +}) +} catch (err) { + console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getQuaternion9+ + +getQuaternion(rotationVector: Array<number>, callback: AsyncCallback): void + +Obtains the quaternion from a rotation vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | ------- | -| gravity | Array<number> | Yes | Gravity vector.| -| geomagnetic | Array<number> | Yes | Geomagnetic vector.| -| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getQuaternion](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; +```js +try { + sensor.getQuaternion ([0.20046076, 0.21907, 0.73978853, 0.60376877], function(data) { + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } - for (var i=0; i < data.rotation.length; i++) { - console.info("data[" + i + "]: " + data[i]) + }) +} catch (err) { + console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getQuaternion9+ + +getQuaternion(rotationVector: Array<number>): Promise + +Obtains the quaternion from a rotation vector. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------ | +| Promise<Array<number>> | Callback used to return the quaternion.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getQuaternion](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + const promise = sensor.getQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('getQuaternionn_promise successed'); + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) +} catch (err) { + console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getOrientation9+ + +getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback): void + +Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | --------------------------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getOrientation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.getOrientation([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { + console.info("SensorJsAPI--->Successed to get getOrientation interface get data: " + data); + for (var i = 1; i < data.length; i++) { + console.info('sensor_getOrientation_callback ' + data[i]); } }) - ``` +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` +## sensor.getOrientation9+ -## sensor.createRotationMatrix +getOrientation(rotationMatrix: Array<number>): Promise -createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> +Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a promise to return the result. +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix.| + +**Return value** + +| Type | Description | +| ---------------------------------- | --------------------------------- | +| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getOrientation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + const promise = sensor.getOrientation([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('sensor_getOrientation_Promise success', data); + for (var i = 1; i < data.length; i++) { + console.info('sensor_getOrientation_promise ' + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getRotationMatrix9+ + +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void + +Obtains the rotation matrix based on a gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | -------------- | +| gravity | Array<number> | Yes | Gravity vector.| +| geomagnetic | Array<number> | Yes | Geomagnetic vector.| +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(data) { + console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); + }) +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getRotationMatrix9+ + +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> + +Obtains the rotation matrix based on a gravity vector and geomagnetic vector. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------- | ---- | ------- | -| gravity | Array<number> | Yes | Gravity vector.| -| geomagnetic | Array<number> | Yes | Geomagnetic vector.| +| Name | Type | Mandatory| Description | +| ----------- | ------------------- | ---- | -------------- | +| gravity | Array<number> | Yes | Gravity vector.| +| geomagnetic | Array<number> | Yes | Geomagnetic vector.| **Return value** -| Type | Description | -| ---------------------------------------- | ------- | +| Type | Description | +| ------------------------------------------------------------ | -------------- | | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** - ```js - const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); +```js +try { + const promise = sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); promise.then((data) => { - console.info('createRotationMatrix_promise successed'); - for (var i=0; i < data.rotation.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } + console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); }).catch((err) => { console.info('promise failed'); }) - ``` +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getSensorLists9+ +## sensor.getSensorList9+ - getSensorLists(callback: AsyncCallback): void + getSensorList(callback: AsyncCallback): void Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. @@ -2394,28 +3020,36 @@ Obtains information about all sensors on the device. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback | Yes | Callback used to return the sensor list.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ---------------- | +| callback | AsyncCallback | Yes | Callback used to return the sensor list.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSensorList](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSensorList((error, data) => { - if (error) { - console.error('getSensorList failed'); - } else { - console.info("getSensorList callback in" + data.length); +try { + sensor.getSensorList((data) => { + console.info('getSensorList callback in ' + data.length); for (var i = 0; i < data.length; i++) { console.info("getSensorList " + JSON.stringify(data[i])); } - } -}); + }); +} catch (err) { + console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` -## sensor.getSensorLists9+ +## sensor.getSensorList9+ - getSensorLists(): Promise< Array<Sensor>> + getSensorList(): Promise< Array<Sensor>> Obtains information about all sensors on the device. This API uses a promise to return the result. @@ -2423,26 +3057,38 @@ Obtains information about all sensors on the device. This API uses a promise to **Return value** -| Name | Type | Mandatory| Description | -| ------- | --------------------------------------- | ---- | ---------------- | -| promise | Promise | Yes | Promise used to return the sensor list.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ---------------- | +| promise | Promise | Yes | Promise used to return the sensor list.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSensorList](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSensorList().then((data) => { - console.info("getSensorList promise in" + data.length); - for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); - } -}, (error)=>{ - console.error('getSensorList failed'); -}); +try { + sensor.getSensorList().then((data) => { + console.info('getSensorList promise in ' + data.length); + for (var i = 0; i < data.length; i++) { + console.info("getSensorList " + JSON.stringify(data[i])); + } + }, (error)=>{ + console.error('getSensorList failed'); + }); +} catch (err) { + console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` ## sensor.getSingleSensor9+ -getSingleSensor(type: SensorType, callback: AsyncCallback<sensor>): void +getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void Obtains information about the sensor of a specific type. This API uses an asynchronous callback to return the result. @@ -2450,26 +3096,34 @@ Obtains information about the sensor of a specific type. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ---------------- | -| type | SensorType | Yes | Sensor type. | -| callback | AsyncCallback<[Sensor](#sensor)> | Yes | Callback used to return the sensor information.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------------- | +| type | [SensorId](#sensorid9) | Yes | Sensor type. | +| callback | AsyncCallback<[Sensor](#sensor9)> | Yes | Callback used to return the sensor information.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSingleSensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js - sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { - if (error) { - console.error('getSingleSensor failed'); - } else { - console.info("getSingleSensor " + JSON.stringify(data)); - } -}); +try { + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { + console.info('getSingleSensor ' + JSON.stringify(data)); + }); +} catch (err) { + console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` ## sensor.getSingleSensor9+ - getSingleSensor(type: SensorType,): Promise<Sensor> + getSingleSensor(type: SensorId): Promise<Sensor> Obtains information about the sensor of a specific type. This API uses a promise to return the result. @@ -2477,58 +3131,98 @@ Obtains information about the sensor of a specific type. This API uses a promise **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------ | -| type | SensorType | Yes | Sensor type.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------ | +| type | [SensorId](#sensorid9) | Yes | Sensor type.| **Return value** -| Name | Type | Mandatory| Description | -| ------- | -------------------------------- | ---- | ---------------- | -| promise | Promise<[Sensor](#sensor)> | Yes | Promise used to return the sensor information.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------- | ---- | ---------------- | +| promise | Promise<[Sensor](#sensor9)> | Yes | Promise used to return the sensor information.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSingleSensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { - console.info("getSingleSensor " + JSON.stringify(data)); -}, (error)=>{ - console.error('getSingleSensor failed'); -}); +try { + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { + console.info('getSingleSensor '+ JSON.stringify(data)); + }, (error)=>{ + console.error('getSingleSensor failed'); + }); +} catch (err) { + console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` -## SensorType +## SensorId9+ + +Enumerates the sensor types. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Default Value| Description | +| --------------------------- | ------ | ---------------------- | +| ACCELEROMETER | 1 | Acceleration sensor. | +| GYROSCOPE | 2 | Gyroscope sensor. | +| AMBIENT_LIGHT | 5 | Ambient light sensor. | +| MAGNETIC_FIELD | 6 | Magnetic field sensor. | +| BAROMETER | 8 | Barometer sensor. | +| HALL | 10 | Hall effect sensor. | +| PROXIMITY | 12 | Proximity sensor. | +| HUMIDITY | 13 | Humidity sensor. | +| ORIENTATION | 256 | Orientation sensor. | +| GRAVITY | 257 | Gravity sensor. | +| LINEAR_ACCELEROMETER | 258 | Linear acceleration sensor. | +| ROTATION_VECTOR | 259 | Rotation vector sensor. | +| AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | +| MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | +| GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | +| SIGNIFICANT_MOTION | 264 | Significant motion sensor. | +| PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | +| PEDOMETER | 266 | Pedometer sensor. | +| HEART_RATE | 278 | Heart rate sensor. | +| WEAR_DETECTION | 280 | Wear detection sensor. | +| ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| + +## SensorType(deprecated) Enumerates the sensor types. **System capability**: SystemCapability.Sensors.Sensor -| Name | Default Value | Description | -| ---------------------------------------- | ---- | ----------- | -| SENSOR_TYPE_ID_ACCELEROMETER | 1 | Acceleration sensor. | -| SENSOR_TYPE_ID_GYROSCOPE | 2 | Gyroscope sensor. | -| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | Ambient light sensor. | -| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | Magnetic field sensor. | -| SENSOR_TYPE_ID_BAROMETER | 8 | Barometer sensor. | -| SENSOR_TYPE_ID_HALL | 10 | Hall effect sensor. | -| SENSOR_TYPE_ID_PROXIMITY | 12 | Proximity sensor. | -| SENSOR_TYPE_ID_HUMIDITY | 13 | Humidity sensor. | -| SENSOR_TYPE_ID_ORIENTATION | 256 | Orientation sensor. | -| SENSOR_TYPE_ID_GRAVITY | 257 | Gravity sensor. | -| SENSOR_TYPE_ID_LINEAR_ACCELERATIONdeprecated | 258 | Linear acceleration sensor. | -| SENSOR_TYPE_ID_LINEAR_ACCELEROMETER | 258 | Linear acceleration sensor. | -| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | Rotation vector sensor. | -| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | -| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | -| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | -| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | Significant motion sensor. | -| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | -| SENSOR_TYPE_ID_PEDOMETER | 266 | Pedometer sensor. | -| SENSOR_TYPE_ID_HEART_RATEdeprecated | 278 | Heart rate sensor. | -| SENSOR_TYPE_ID_HEART_BEAT_RATE | 278 | Heart rate sensor. | -| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | Wear detection sensor. | -| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| +| Name | Default Value| Description | +| ------------------------------------------ | ------ | ---------------------- | +| SENSOR_TYPE_ID_ACCELEROMETER | 1 | Acceleration sensor. | +| SENSOR_TYPE_ID_GYROSCOPE | 2 | Gyroscope sensor. | +| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | Ambient light sensor. | +| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | Magnetic field sensor. | +| SENSOR_TYPE_ID_BAROMETER | 8 | Barometer sensor. | +| SENSOR_TYPE_ID_HALL | 10 | Hall effect sensor. | +| SENSOR_TYPE_ID_PROXIMITY | 12 | Proximity sensor. | +| SENSOR_TYPE_ID_HUMIDITY | 13 | Humidity sensor. | +| SENSOR_TYPE_ID_ORIENTATION | 256 | Orientation sensor. | +| SENSOR_TYPE_ID_GRAVITY | 257 | Gravity sensor. | +| SENSOR_TYPE_ID_LINEAR_ACCELERATION | 258 | Linear acceleration sensor. | +| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | Rotation vector sensor. | +| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | +| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | +| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | +| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | Significant motion sensor. | +| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | +| SENSOR_TYPE_ID_PEDOMETER | 266 | Pedometer sensor. | +| SENSOR_TYPE_ID_HEART_RATE | 278 | Heart rate sensor. | +| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | Wear detection sensor. | +| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| ## Response @@ -2541,7 +3235,7 @@ Describes the timestamp of the sensor data. | --------- | -------- | ---- | ---- | ------------------------ | | timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| -## Sensor +## Sensor9+ Describes the sensor information. @@ -2553,8 +3247,10 @@ Describes the sensor information. | venderName | string | Vendor of the sensor. | | firmwareVersion | string | Firmware version of the sensor. | | hardwareVersion | string | Hardware version of the sensor. | -| sensorTypeId | number | Sensor type ID. | +| sensorId | number | Sensor type ID. | | maxRange | number | Maximum measurement range of the sensor.| +| minSamplePeriod | number | Minimum sampling period. | +| maxSamplePeriod | number | Maximum sampling period. | | precision | number | Precision of the sensor. | | power | number | Power supply of the sensor. | @@ -2565,11 +3261,11 @@ Describes the acceleration sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ---------------------- | -| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ------------------------------------ | +| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| ## LinearAccelerometerResponse @@ -2579,11 +3275,11 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------------------- | +| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| ## AccelerometerUncalibratedResponse @@ -2593,14 +3289,14 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ---------------------------- | -| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | -| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | -| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | -| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | -| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| -| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------------ | +| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | +| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | +| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | +| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | +| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| +| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | ## GravityResponse @@ -2610,11 +3306,11 @@ Describes the gravity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------------------- | +| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| ## OrientationResponse @@ -2624,11 +3320,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ----------------- | -| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| -| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| -| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | --------------------------------- | +| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| ## RotationVectorResponse @@ -2638,12 +3334,12 @@ Describes the rotation vector sensor data. It extends from [Response](#response) **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | --------- | -| x | number | Yes | Yes | X-component of the rotation vector.| -| y | number | Yes | Yes | Y-component of the rotation vector.| -| z | number | Yes | Yes | Z-component of the rotation vector.| -| w | number | Yes | Yes | Scalar. | +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ----------------- | +| x | number | Yes | Yes | X-component of the rotation vector.| +| y | number | Yes | Yes | Y-component of the rotation vector.| +| z | number | Yes | Yes | Z-component of the rotation vector.| +| w | number | Yes | Yes | Scalar. | ## GyroscopeResponse @@ -2653,11 +3349,11 @@ Describes the gyroscope sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------- | -| x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s.| -| y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s.| -| z | number | Yes | Yes | Angular velocity of rotation around the z-axis of the device, in rad/s.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | -------------------------------- | +| x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s.| +| y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s.| +| z | number | Yes | Yes | Angular velocity of rotation around the z-axis of the device, in rad/s.| ## GyroscopeUncalibratedResponse @@ -2667,14 +3363,14 @@ Describes the uncalibrated gyroscope sensor data. It extends from [Response](#re **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | -| y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | -| z | number | Yes | Yes | Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s. | -| biasX | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| -| biasY | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| -| biasZ | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------ | +| x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | +| y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | +| z | number | Yes | Yes | Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s. | +| biasX | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| +| biasY | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| +| biasZ | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| ## SignificantMotionResponse @@ -2684,9 +3380,9 @@ Describes the significant motion sensor data. It extends from [Response](#respon **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | -| scalar | number | Yes | Yes | Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| scalar | number | Yes | Yes | Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| ## ProximityResponse @@ -2696,9 +3392,9 @@ Describes the proximity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ---------------------------- | -| distance | number | Yes | Yes | Proximity between the visible object and the device monitor. The value **0** means the two are close to each other, and **1** means that they are far away from each other.| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | ------------------------------------------------------ | +| distance | number | Yes | Yes | Proximity between the visible object and the device monitor. The value **0** means the two are close to each other, and **1** means that they are far away from each other.| ## LightResponse @@ -2708,9 +3404,9 @@ Describes the ambient light sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ----------- | -| intensity | number | Yes | Yes | Illumination, in lux.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ---------------------- | +| intensity | number | Yes | Yes | Illumination, in lux.| ## HallResponse @@ -2746,14 +3442,14 @@ Describes the uncalibrated magnetic field sensor data. It extends from [Response **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ---------------------- | -| x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | -| y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | -| z | number | Yes | Yes | Uncalibrated magnetic field strength on the z-axis, in μT. | -| biasX | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| -| biasY | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| -| biasZ | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | -------------------------------------- | +| x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | +| y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | +| z | number | Yes | Yes | Uncalibrated magnetic field strength on the z-axis, in μT. | +| biasX | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| +| biasY | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| +| biasZ | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| ## PedometerResponse @@ -2763,9 +3459,9 @@ Describes the pedometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | -------- | -| steps | number | Yes | Yes | Number of steps a user has walked.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ---------------- | +| steps | number | Yes | Yes | Number of steps a user has walked.| ## HumidityResponse @@ -2775,9 +3471,9 @@ Describes the humidity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ------------------------------------ | -| humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | --------------------------------------------------------- | +| humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| ## PedometerDetectionResponse @@ -2787,9 +3483,9 @@ Describes the pedometer detection sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | -| scalar | number | Yes | Yes | Pedometer detection. This parameter specifies whether a user takes a step. The value **0** means that the user does not take a step, and **1** means that the user takes a step.| +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| scalar | number | Yes | Yes | Pedometer detection. This parameter specifies whether a user takes a step. The value **0** means that the user does not take a step, and **1** means that the user takes a step.| ## AmbientTemperatureResponse @@ -2799,9 +3495,9 @@ Describes the ambient temperature sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----------- | ------ | ---- | ---- | ------------- | -| temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| +| Name | Type| Readable| Writable| Description | +| ----------- | -------- | ---- | ---- | -------------------------- | +| temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| ## BarometerResponse @@ -2811,9 +3507,9 @@ Describes the barometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ------------ | -| pressure | number | Yes | Yes | Atmospheric pressure, in pascal.| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | ------------------------ | +| pressure | number | Yes | Yes | Atmospheric pressure, in pascal.| ## HeartRateResponse @@ -2823,9 +3519,9 @@ Describes the heart rate sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | --------------------- | -| heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | --------------------------------------- | +| heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| ## WearDetectionResponse @@ -2835,9 +3531,9 @@ Describes the wear detection sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------- | -| value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------------ | +| value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| ## Options @@ -2846,9 +3542,9 @@ Describes the sensor data reporting frequency. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Description | -| -------- | ------ | --------------------------- | -| interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| +| Name | Type| Description | +| -------- | -------- | ------------------------------------------- | +| interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| ## RotationMatrixResponse @@ -2856,10 +3552,10 @@ Describes the response for setting the rotation matrix. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----------- | ------------------- | ---- | ---- | ----- | -| rotation | Array<number> | Yes | Yes | Rotation matrix.| -| inclination | Array<number> | Yes | Yes | Inclination matrix.| +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------- | ---- | ---- | ---------- | +| rotation | Array<number> | Yes | Yes | Rotation matrix.| +| inclination | Array<number> | Yes | Yes | Inclination matrix.| ## CoordinatesOptions @@ -2868,10 +3564,10 @@ Describes the coordinate options. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------ | -| x | number | Yes | Yes | X coordinate direction.| -| y | number | Yes | Yes | Y coordinate direction.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ----------- | +| x | number | Yes | Yes | X coordinate direction.| +| y | number | Yes | Yes | Y coordinate direction.| ## GeomagneticResponse @@ -2880,15 +3576,15 @@ Describes a geomagnetic response object. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------------- | ------ | ---- | ---- | ------------------------- | -| x | number | Yes | Yes | North component of the geomagnetic field. | -| y | number | Yes | Yes | East component of the geomagnetic field. | -| z | number | Yes | Yes | Vertical component of the geomagnetic field. | -| geomagneticDip | number | Yes | Yes | Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector. | -| deflectionAngle | number | Yes | Yes | Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| -| levelIntensity | number | Yes | Yes | Horizontal intensity of the magnetic field vector field. | -| totalIntensity | number | Yes | Yes | Total intensity of the magnetic field vector. | +| Name | Type| Readable| Writable| Description | +| --------------- | -------- | ---- | ---- | -------------------------------------------------- | +| x | number | Yes | Yes | North component of the geomagnetic field. | +| y | number | Yes | Yes | East component of the geomagnetic field. | +| z | number | Yes | Yes | Vertical component of the geomagnetic field. | +| geomagneticDip | number | Yes | Yes | Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector. | +| deflectionAngle | number | Yes | Yes | Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| +| levelIntensity | number | Yes | Yes | Horizontal intensity of the magnetic field vector field. | +| totalIntensity | number | Yes | Yes | Total intensity of the magnetic field vector. | ## LocationOptions @@ -2896,8 +3592,2607 @@ Describes the geographical location. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ----- | -| latitude | number | Yes | Yes | Latitude. | -| longitude | number | Yes | Yes | Longitude. | -| altitude | number | Yes | Yes | Altitude.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ---------- | +| latitude | number | Yes | Yes | Latitude. | +| longitude | number | Yes | Yes | Longitude. | +| altitude | number | Yes | Yes | Altitude.| + +## sensor.on(deprecated) + +### ACCELEROMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void + +Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ACCELEROMETER](#accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### LINEAR_ACCELERATION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void + +Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +### LINEAR_ACCELEROMETER9+ + +on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, + options?: Options): void + +Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void + +Subscribes to data changes of the uncalibrated acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + ``` + +### GRAVITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void + +Subscribes to data changes of the gravity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GRAVITY](#gravity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### GYROSCOPE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void + +Subscribes to data changes of the gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GYROSCOPE](#gyroscope9) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void + +Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + ``` + +### SIGNIFICANT_MOTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void + +Subscribes to data changes of the significant motion sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.SIGNIFICANT_MOTION](#significant_motion9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, + {interval: 10000000} + ); + ``` + +### PEDOMETER_DETECTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void + +Subscribes to data changes of the pedometer detection sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PEDOMETER_DETECTION](#pedometer_detection9) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, + {interval: 10000000} + ); + ``` + +### PEDOMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void + +Subscribes to data changes of the pedometer sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PEDOMETER](#pedometer9) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ + console.info('Steps: ' + data.steps); + }, + {interval: 10000000} + ); + ``` + +### AMBIENT_TEMPERATURE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void + +Subscribes to data changes of the ambient temperature sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.AMBIENT_TEMPERATURE](#ambient_temperature9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ + console.info('Temperature: ' + data.temperature); + }, + {interval: 10000000} + ); + + ``` + +### MAGNETIC_FIELD(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void + +Subscribes to data changes of the magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.MAGNETIC_FIELD](#magnetic_field9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + + ``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void + +Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + + ``` + +### PROXIMITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void + +Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PROXIMITY](#proximity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ + console.info('Distance: ' + data.distance); + }, + {interval: 10000000} + ); + + ``` + +### HUMIDITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void + +Subscribes to data changes of the humidity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HUMIDITY](#humidity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ + console.info('Humidity: ' + data.humidity); + }, + {interval: 10000000} + ); + + ``` + +### BAROMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void + +Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.BAROMETER](#barometer9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ + console.info('Atmospheric pressure: ' + data.pressure); + }, + {interval: 10000000} + ); + + ``` + +### HALL(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void + +Subscribes to data changes of the Hall effect sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HALL](#hall9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ + console.info('Status: ' + data.status); + }, + {interval: 10000000} + ); + + ``` + +### AMBIENT_LIGHT(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void + +Subscribes to data changes of the ambient light sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.AMBIENT_LIGHT](#ambient_light9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ + console.info(' Illumination: ' + data.intensity); + }, + {interval: 10000000} + ); + ``` + +### ORIENTATION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void + +Subscribes to data changes of the orientation sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ORIENTATION](#orientation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }, + {interval: 10000000} + ); + + ``` + +### HEART_RATE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void + +Subscribes to only one data change of the heart rate sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HEART_BEAT_RATE](#heart_beat_rate9) instead. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### HEART_BEAT_RATE9+ + +on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, + options?: Options): void + +Subscribes to only one data change of the heart rate sensor. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +**Example** + +```js +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE,function(data){ + console.info("Heart rate: " + data.heartRate); +}, + {interval: 10000000} +); + +``` + +### ROTATION_VECTOR(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void + +Subscribes to data changes of the rotation vector sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ROTATION_VECTOR](#rotation_vector9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, + {interval: 10000000} + ); + ``` + +### WEAR_DETECTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void + +Subscribes to data changes of the wear detection sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.WEAR_DETECTION](#wear_detection9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ + console.info('Wear status: ' + data.value); + }, + {interval: 10000000} + ); + + ``` + +## sensor.once(deprecated) + +### ACCELEROMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void + +Subscribes to only one data change of the acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ACCELEROMETER](#accelerometer9-1) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### LINEAR_ACCELERATION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void + +Subscribes to only one data change of the linear acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELERATION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +### LINEAR_ACCELEROMETER9+ + +once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void + +Subscribes to only one data change of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELERATION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9-1) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | + +**Example** + + ``` + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + + ``` + +### GRAVITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void + +Subscribes to only one data change of the gravity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GRAVITY](#gravity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### GYROSCOPE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void + +Subscribes to only one data change of the gyroscope sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GYROSCOPE](#gyroscope9-1) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated gyroscope sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9-1) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + + ``` + +### SIGNIFICANT_MOTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void + +Subscribes to only one data change of the significant motion sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.SIGNIFICANT_MOTION](#significant_motion9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); + + ``` + +### PEDOMETER_DETECTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void + +Subscribes to only one data change of the pedometer detection sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PEDOMETER_DETECTION](#pedometer_detection9-1) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); + + ``` + +### PEDOMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void + +Subscribes to only one data change of the pedometer sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PEDOMETER](#pedometer9-1) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { + console.info('Steps: ' + data.steps); + } + ); + ``` + +### AMBIENT_TEMPERATURE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void + +Subscribes to only one data change of the ambient temperature sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.AMBIENT_TEMPERATURE](#ambient_temperature9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { + console.info('Temperature: ' + data.temperature); + } + ); + + ``` + +### MAGNETIC_FIELD(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void + +Subscribes to only one data change of the magnetic field sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.MAGNETIC_FIELD](#magnetic_field9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated magnetic field sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + + ``` + +### PROXIMITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void + +Subscribes to only one data change of the proximity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PROXIMITY](#proximity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { + console.info('Distance: ' + data.distance); + } + ); + ``` + +### HUMIDITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void + +Subscribes to only one data change of the humidity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HUMIDITY](#humidity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { + console.info('Humidity: ' + data.humidity); + } + ); + + ``` + +### BAROMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void + +Subscribes to only one data change of the barometer sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.BAROMETER](#barometer9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + ); + + ``` + +### HALL(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void + +Subscribes to only one data change of the Hall effect sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HALL](#hall9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { + console.info('Status: ' + data.status); + } + ); + + ``` + +### AMBIENT_LIGHT(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void + +Subscribes to only one data change of the ambient light sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.AMBIENT_LIGHT](#ambient_light9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { + console.info(' Illumination: ' + data.intensity); + } + ); + + ``` + +### ORIENTATION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void + +Subscribes to only one data change of the orientation sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ORIENTATION](#orientation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + ); + + ``` + +### ROTATION_VECTOR(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void + +Subscribes to only one data change of the rotation vector sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ROTATION_VECTOR](#rotation_vector9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + ); + + ``` + +### HEART_RATE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void + +Subscribes to only one data change of the heart rate sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HEART_BEAT_RATE](#heart_beat_rate9) instead. + +**Required permissions**: ohos.permission.HEART_RATE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### HEART_BEAT_RATE9+ + +once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void + +Subscribes to only one data change of the heart rate sensor. + +**Required permissions**: ohos.permission.HEART_RATE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, function(data) { + console.info("Heart rate: " + data.heartRate); + } + ); + + ``` + +### WEAR_DETECTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void + +Subscribes to only one data change of the wear detection sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.WEAR_DETECTION](#wear_detection9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { + console.info("Wear status: "+ data.value); + } + ); + + ``` + +## sensor.off(deprecated) + +### ACCELEROMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ACCELEROMETER](#accelerometer9-2) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('x-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); + +``` + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9-2) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); + +``` + +### AMBIENT_LIGHT(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.AMBIENT_LIGHT](#ambient_light9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | + +**Example** + +```js +function callback(data) { + console.info(' Illumination: ' + data.intensity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); + +``` + +### AMBIENT_TEMPERATURE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.AMBIENT_TEMPERATURE](#ambient_temperature9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Temperature: ' + data.temperature); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); + +``` + +### BAROMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.BAROMETER](#barometer9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Atmospheric pressure: ' + data.pressure); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); +``` + +### GRAVITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GRAVITY](#gravity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); +``` + +### GYROSCOPE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GYROSCOPE](#gyroscope9-2) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); + +``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9-2) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); + +``` + +### HALL(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HALL](#hall9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Status: ' + data.status); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); + +``` + +### HEART_RATE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HEART_BEAT_RATE](#heart_beat_rate9) instead. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### HEART_BEAT_RATE9+ + +off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +**Example** + +```js +function callback(data) { + console.info("Heart rate: " + data.heartRate); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback); + +``` + +### HUMIDITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HUMIDITY](#humidity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Humidity: ' + data.humidity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); + +``` + +### LINEAR_ACCELERATION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +### LINEAR_ACCELEROMETER9+ + +off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback?:Callback<LinearAccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback); + +``` + +### MAGNETIC_FIELD(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.MAGNETIC_FIELD](#magnetic_field9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); + +``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); + +``` + +### ORIENTATION(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ORIENTATION](#orientation9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | + +**Example** + +```js +function callback(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); + +``` + +### PEDOMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PEDOMETER](#pedometer9-2) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Steps: ' + data.steps); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); + +``` + +### PEDOMETER_DETECTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PEDOMETER_DETECTION](#pedometer_detection9-2) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); +``` + +### PROXIMITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PROXIMITY](#proximity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Distance: ' + data.distance); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); +``` + +### ROTATION_VECTOR(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ROTATION_VECTOR](#rotation_vector9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); + +``` + +### SIGNIFICANT_MOTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.SIGNIFICANT_MOTION](#significant_motion9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); + +``` + +### WEAR_DETECTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.WEAR_DETECTION](#wear_detection9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | + +**Example** + +```js +function accCallback(data) { + console.info('Wear status: ' + data.value); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); + +``` + +## sensor.transformCoordinateSystem(deprecated) + +transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.transformRotationMatrix](#sensortransformrotationmatrix9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ----------------------------------------- | --------- | ------------------------------------------------------------ | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated. | + +**Example** + +```js +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { + if (err) { + console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); + return; + } + console.info("Operation successed. Data obtained: " + data); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }) + +``` + +## sensor.transformCoordinateSystem(deprecated) + +transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.transformRotationMatrix](#sensortransformrotationmatrix9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ----------------------------------------- | --------- | ----------------------------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated. | + +**Example** + +```js +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + promise.then((data) => { + console.info("Operation successed."); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }).catch((err) => { + console.info("Operation failed"); +}) + +``` + +## sensor.getGeomagneticField(deprecated) + +getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void + +Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getGeomagneticInfo](#sensorgetgeomagneticinfo9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds. | +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | + +**Example** + +```js +sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { + if (err) { + console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); +}); + +``` + +## sensor.getGeomagneticField(deprecated) + +getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> + +Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getGeomagneticInfo](#sensorgetgeomagneticinfo9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ----------------------------------- | --------- | ------------------------------------------------------------ | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------------- | --------------------------------------------- | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | + +**Example** + + ```js + const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); + promise.then((data) => { + console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + }).catch((reason) => { + console.info('Operation failed.'); + }) + + ``` + +## sensor.getAltitude(deprecated) + +getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getDeviceAltitude](#sensorgetdevicealtitude9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa. | +| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | + +**Example** + + ```js + sensor.getAltitude(0, 200, function(err, data) { + if (err) { + console.error( + "Operation failed. Error code: " + err.code + ", message: " + err.message); + return; + } + console.info("Successed to get getAltitude interface get data: " + data); + }); + + ``` + +## sensor.getAltitude(deprecated) + +getAltitude(seaPressure: number, currentPressure: number): Promise<number> + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getDeviceAltitude](#sensorgetdevicealtitude9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ------ | --------- | ------------------------------------------------------------ | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------- | +| Promise<number> | Promise used to return the altitude, in meters. | + +**Example** + + ```js + const promise = sensor.getAltitude(0, 200); + promise.then((data) => { + console.info(' sensor_getAltitude_Promise success', data); + }).catch((err) => { + console.error("Operation failed"); + }) + + ``` + + +## sensor.getGeomagneticDip(deprecated) + +getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void + +Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getInclination](#sensorgetinclination9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------------- | --------------------------- | --------- | ----------------------------------------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | +| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians. | + +**Example** + + ```js + sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + + err.message); + return; + } + console.info("Successed to get getGeomagneticDip interface get data: " + data); + }) + ``` + +## sensor.getGeomagneticDip(deprecated) + +getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> + +Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getInclination](#sensorgetinclination9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------------- | ------------------- | --------- | ------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------------------------- | +| Promise<number> | Promise used to return the magnetic dip, in radians. | + +**Example** + + ```js + const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('getGeomagneticDip_promise successed', data); + }).catch((err) => { + console.error("Operation failed"); + }) + ``` + +## sensor. getAngleModify(deprecated) + +getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void + +Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getAngleVariation](#sensorgetanglevariation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes. | + +**Example** + + ```js + sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { + if (err) { + console.error('Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + + ``` + + +## sensor. getAngleModify(deprecated) + +getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> + +Obtains the angle change between two rotation matrices. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getAngleVariation](#sensorgetanglevariation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------------- | ------------------- | --------- | -------------------------- | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes. | + +**Example** + + ```js + const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); + promise.then((data) => { + console.info('getAngleModifiy_promise success'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((reason) => { + console.info("promise::catch", reason); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + +Converts a rotation vector into a rotation matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | -------------------------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix. | + +**Example** + + ```js + sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> + +Converts a rotation vector into a rotation matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | --------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------- | +| Promise<Array<number>> | Promise used to return the rotation matrix. | + +**Example** + + ```js + const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('createRotationMatrix_promise success'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((reason) => { + console.info("promise::catch", reason); + }) + + ``` + + +## sensor.createQuaternion(deprecated) + +createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + +Converts a rotation vector into a quaternion. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getQuaternion](#sensorgetquaternion9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | --------------------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | + +**Example** + + ```js + sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + + ``` + + +## sensor.createQuaternion(deprecated) + +createQuaternion(rotationVector: Array<number>): Promise<Array<number>> + +Converts a rotation vector into a quaternion. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getQuaternion](#sensorgetquaternion9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | --------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | + +**Return value** + +| Type | Description | +| ---------------------------------- | -------------------------------------- | +| Promise<Array<number>> | Promise used to return the quaternion. | + +**Example** + + ```js + const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('createQuaternion_promise successed'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + +## sensor.getDirection(deprecated) + +getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void + +Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getOrientation](#sensorgetorientation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes. | + +**Example** + + ```js + sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); + for (var i = 1; i < data.length; i++) { + console.info("sensor_getDirection_callback" + data[i]); + } + }) + + ``` + + +## sensor.getDirection(deprecated) + +getDirection(rotationMatrix: Array<number>): Promise<Array<number>> + +Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getOrientation](#sensorgetorientation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | ---------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes. | + +**Example** + + ```js + const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('sensor_getAltitude_Promise success', data); + for (var i = 1; i < data.length; i++) { + console.info("sensor_getDirection_promise" + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void + +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------------------------------------ | --------- | -------------------------------------------- | +| gravity | Array<number> | Yes | Gravity vector. | +| geomagnetic | Array<number> | Yes | Geomagnetic vector. | +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix. | + +**Example** + + ```js + sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { + if (err) { + console.error('error code is: ' + err.code + ', message: ' + err.message); + return; + } + console.info(JSON.stringify(data)); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> + +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-3) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | --------- | ------------------- | +| gravity | Array<number> | Yes | Gravity vector. | +| geomagnetic | Array<number> | Yes | Geomagnetic vector. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------- | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix. | + +**Example** + + ```js + const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); + promise.then((data) => { + console.info(JSON.stringify(data)); + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-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 ae9a1ece9c9b419ea23162f354d7a428bd104a6c..6622b4b719e95f2c87af19653fbf8a89905239f2 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -2683,8 +2683,6 @@ getOpKey(slotId: number): Promise Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2716,8 +2714,6 @@ getOpName(slotId: number, callback: AsyncCallback): void Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2742,8 +2738,6 @@ getOpName(slotId: number): Promise Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 77dd0bc0560d11837a5cfbb68f38fd3f39075310..cd0995948cc8354d05845c7156abcdfdfb558bda 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -316,7 +316,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { return; } console.log('bind success'); - let promise = udp.getState({}); + let promise = udp.getState(); promise.then(data => { console.log('getState success:' + JSON.stringify(data)); }).catch(err => { @@ -626,7 +626,7 @@ Defines the parameters for sending data over the UDPSocket connection. | Name | Type | Mandatory| Description | | ------- | ---------------------------------- | ---- | -------------- | -| data | string | Yes | Data to send. | +| data | string \| ArrayBuffer7+ | Yes | Data to send. | | address | [NetAddress](#netaddress) | Yes | Destination address.| ## UDPExtraOptions @@ -1434,7 +1434,7 @@ Defines the parameters for sending data over the TCPSocket connection. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| data | string | Yes | Data to send. | +| data | string\| ArrayBuffer7+ | Yes | Data to send. | | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| ## TCPExtraOptions diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 658082d2690c0ab00d76959a1a7ce1c97574ce5d..10f08e3b588e7c03d44ef3eac6ade39a42a5febe 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -29,15 +29,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | volumeUuid | string | Yes | UUID of the volume.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| volumeUuid | string | Yes | UUID of the volume.| **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<number> | Promise used to return the total size of the volume.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<number> | Promise used to return the total size of the volume.| **Example** @@ -66,10 +66,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| volumeUuid | string | Yes | UUID of the volume. | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| **Example** @@ -97,15 +97,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | volumeUuid | string | Yes | UUID of the volume.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| volumeUuid | string | Yes | UUID of the volume.| **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the volume.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the available space of the volume.| **Example** @@ -135,10 +135,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | ---------------------------- | - | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ---------------------------- | +| volumeUuid | string | Yes | UUID of the volume. | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| **Example** @@ -166,15 +166,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ----------- | ------ | ---- | -------- | - | packageName | string | Yes | Bundle name of the application.| +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------- | +| packageName | string | Yes | Bundle name of the application.| **Return value** - | Type | Description | - | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| +| Type | Description | +| ------------------------------------------ | -------------------------- | +| Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| **Example** @@ -203,10 +203,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | packageName | string | Yes | Bundle name of the application.| - | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------ | +| packageName | string | Yes | Bundle name of the application.| +| callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| **Example** @@ -228,9 +228,9 @@ Asynchronously obtains space information of the current third-party application. **Return value** - | Type | Description | - | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | +| Type | Description | +| ------------------------------------------ | -------------------------- | +| Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | **Example** @@ -249,9 +249,9 @@ Asynchronously obtains space information of the current third-party application. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------ | +| callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | **Example** @@ -294,9 +294,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the total space of the built-in memory card. | +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the total space of the built-in memory card. | **Example** @@ -321,9 +321,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------ | ---- | ------------------------ | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------ | ---- | ------------------------ | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| **Example** @@ -351,9 +351,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the built-in memory card.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the available space of the built-in memory card.| **Example** @@ -379,9 +379,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------------------ | ---- | ------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------- | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| **Example** @@ -408,9 +408,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<number> | Promise used to return the system space obtained.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<number> | Promise used to return the system space obtained.| **Example** @@ -438,9 +438,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| **Example** @@ -467,15 +467,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<[StorageStats](#StorageStats)> | Promise used to return the information obtained.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<[StorageStats](#storagestats9)> | Promise used to return the information obtained.| **Example** @@ -504,10 +504,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | - | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | +| callback | callback:AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index daa6d4aac0d3ea39560a13de07b37c51c8b9226a..0a46cec929810e8f485a66b26445f1e3042b7672 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -1,6 +1,7 @@ # Notification -> ![icon-note.gif]public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.notification`](js-apis-notification.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -51,18 +52,17 @@ Displays a notification. **Example** ```javascript -export default { - show() { - notification.show({ - contentTitle: 'title info', - contentText: 'text', - clickAction: { - bundleName: 'com.example.testapp', - abilityName: 'notificationDemo', - uri: '/path/to/notification', - }, - }); - }, +export default { + show() { + notification.show({ + contentTitle: 'title info', + contentText: 'text', + clickAction: { + bundleName: 'com.example.testapp', + abilityName: 'notificationDemo', + uri: '/path/to/notification', + }, + }); + }, } -; ``` diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index 7d8018a4e82916df0c218a10ca7d5e8fdb9e6364..f3a29a9cc683fecc38b4c935af7607bd2a5415b8 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -63,6 +63,29 @@ promise.then((data) => { }); ``` +## data.getDefaultCellularDataSlotIdSync + +getDefaultCellularDataSlotIdSync(): number + +Obtains the default SIM card used for mobile data synchronously. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| ------ | -------------------------------------------------- | +| number | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Example** + +```js +console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) +``` + + ## data.setDefaultCellularDataSlotId setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-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-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 699ab299f5050594fd943c95e36c0538e9d0ec24..95654a5829967c3e6f3be2be8c5daf3baf527386 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -31,6 +31,14 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | | callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| + **Example** ```js @@ -76,6 +84,14 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | ------------------- | -------------------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 52f5367110bc35c33075ed291a796a657a468816..bda4ad227b32b18130682bb4fe10db9a446535ec 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -433,7 +433,7 @@ ws.off('open', callback1); on\(type: 'message', callback: AsyncCallback\): void -Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). @@ -462,7 +462,7 @@ ws.on('message', (err, value) => { off\(type: 'message', callback?: AsyncCallback\): void -Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 13014cfed8a6cc95d124535c89b399b12348395f..a8221a78898accf8d18724193df311a13693b998 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -302,7 +302,7 @@ Represents the WLAN configuration. ## IpType7+ -Enumerate the IP address types. +Enumerates the IP address types. **System API**: This is a system API. @@ -1851,7 +1851,7 @@ Unregisters the WLAN state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -1909,7 +1909,7 @@ Unregisters the WLAN connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -1952,7 +1952,7 @@ Unregisters the WLAN scan state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiRssiChange')7+ @@ -1988,7 +1988,7 @@ Unregisters the RSSI change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('hotspotStateChange')7+ @@ -2033,7 +2033,7 @@ Unregisters the hotspot state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pStateChange')8+ @@ -2078,7 +2078,7 @@ Unregisters the P2P state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pConnectionChange')8+ @@ -2114,7 +2114,7 @@ Unregisters the P2P connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| -| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDeviceChange')8+ @@ -2150,7 +2150,7 @@ Unregisters the P2P device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| -| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPeerDeviceChange')8+ @@ -2186,7 +2186,7 @@ Unregisters the P2P peer device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| -| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ @@ -2222,7 +2222,7 @@ Unregisters the P2P persistent group state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| -| callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDiscoveryChange')8+ @@ -2265,4 +2265,4 @@ Unregisters the P2P device discovery state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| -| callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/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/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-container-badge.md b/en/application-dev/reference/arkui-js/js-components-container-badge.md index b080f605d5ef2f95faa565d505965190f83db9e4..d9322ba2777470e7396354768fe31c3ee7b9b213 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..3ac87caa897942f38b8863aca8a21b538337aa84 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..f957e14aed43aaef9edb1b15bc543eb0994d2f96 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 @@ -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-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-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_0000001193872492.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png new file mode 100644 index 0000000000000000000000000000000000000000..c564bb26b539f1e48acbdb7f2aeeca8df4e4e798 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png new file mode 100644 index 0000000000000000000000000000000000000000..6c136313fe0c8774d1209a398d16ecc4b58c2bcd Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png new file mode 100644 index 0000000000000000000000000000000000000000..3e7218eb57566d86457a9fbd4a8ed0f0dd490c3f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png new file mode 100644 index 0000000000000000000000000000000000000000..a07986a04b7477eec14c81d08e442d7b332dab83 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png new file mode 100644 index 0000000000000000000000000000000000000000..3d93b0a0a8f5d0b527d407e450a4a13a1de991ab Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png new file mode 100644 index 0000000000000000000000000000000000000000..5c0a336a56d0e5a186bd235cd25f9f5e5e7e644f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png new file mode 100644 index 0000000000000000000000000000000000000000..2b9bc96da366d53da784c92620a69f602f7bff14 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png new file mode 100644 index 0000000000000000000000000000000000000000..27556ea43f7c2ecc65b9425e243ea593f02b08ec Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png new file mode 100644 index 0000000000000000000000000000000000000000..2a5c5649cc0716abc024aa3656924a456216a4c2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png new file mode 100644 index 0000000000000000000000000000000000000000..00097d258d585ec8ad981703c5b265679e867133 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png new file mode 100644 index 0000000000000000000000000000000000000000..1b1cedac00a77279faa829636bc85028fb5ec711 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png new file mode 100644 index 0000000000000000000000000000000000000000..5855095851b92058f270d69a46546db43ec974b8 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png new file mode 100644 index 0000000000000000000000000000000000000000..81710c1186a0c0448d70a443db66c09a4e46d395 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png new file mode 100644 index 0000000000000000000000000000000000000000..5c75654b85d596a346fa5d793ca84991fe859a86 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png new file mode 100644 index 0000000000000000000000000000000000000000..defc3c9eb037c06b894ee2e30563facb8c8375ab Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png new file mode 100644 index 0000000000000000000000000000000000000000..abc9a5667500a749dbceee88aef4caebf5d9df18 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png new file mode 100644 index 0000000000000000000000000000000000000000..241fe8546ea2acfdb7baf2c5e66a8af2f0d7b593 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png new file mode 100644 index 0000000000000000000000000000000000000000..19e99b9ef490fff79e64e33192c97c1a39c6edf9 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png new file mode 100644 index 0000000000000000000000000000000000000000..4558b332925757d97d70ee57182c260804629346 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png new file mode 100644 index 0000000000000000000000000000000000000000..9b35e8e0fc4bb514584813b79e8889cfe65649a7 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png new file mode 100644 index 0000000000000000000000000000000000000000..9e0a95f73b1aec44e6bccd6750a1c9f2815178ee Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png differ diff --git a/en/application-dev/reference/arkui-ts/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/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-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-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-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-drawing-components-path.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md index 96bedd577f9bdf9431957ddd52735bda35a60808..df5bc74f017aedfc698e85fd88f9e39f00bcb29d 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -89,4 +89,4 @@ struct PathExample { } ``` -![zh-cn_image_0000001219744193](figures/zh-cn_image_0000001219744193.png) +![en-us_image_0000001219744193](figures/en-us_image_0000001219744193.png) diff --git a/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md b/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md deleted file mode 100644 index 029a61c9f47bfb216d507b70845c3fc6877ca697..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md +++ /dev/null @@ -1,277 +0,0 @@ -# Interpolation Calculation - -Interpolation calculation can be implemented to set the animation interpolation curve, which is used to construct the step curve, cubic Bezier curve, and spring curve objects. - -> **NOTE** -> -> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```js -import Curves from '@ohos.curves' -``` - - -## Curves.initCurve9+ - -initCurve(curve?: Curve): ICurve - - -Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve | [Curve](#curve-enums)| No | Curve.Linear | Curve type.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Interpolation object of the curve.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -``` - - -## Curves.stepsCurve9+ - -stepsCurve(count: number, end: boolean): ICurve - - -Constructs a step curve object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end point of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.stepsCurve(9, true) // Create a step curve. -``` - - -## Curves.cubicBezierCurve9+ - -cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve - - -Constructs a third-order Bezier curve object. The curve value must be between 0 and 1. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. -``` - - -## Curves.springCurve9+ - -springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve - - -Constructs a spring curve object. - - -**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| -| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.| - - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.springCurve(100, 1, 228, 30) // Create a spring curve. -``` - - -## ICurve - - -### interpolate - -interpolate(fraction: number): number - - -Calculation function of the interpolation curve. Passing a normalized time parameter to this function returns the current interpolation. - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | -------------------------------------------- | -| fraction | number | Yes | Current normalized time. The value ranges from 0 to 1.| - -**Return value** - -| Type | Description | -| ------ | ------------------------------------ | -| number | The curve interpolation corresponding to the normalized time point is returned.| - -**Example** - -```ts -import Curves from '@ohos.curves' -let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. -``` - - -## Curves.init(deprecated) - -init(curve?: Curve): string - - -Implements initialization to create a curve object based on the input parameter. This API is deprecated since API version 9. Use [Curves.initCurve](#curvesinitcurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve |[Curve](#curve-enums)| No | Curve.Linear | Curve type.| - - -## Curves.steps(deprecated) - -steps(count: number, end: boolean): string - - -Constructs a step curve object. This API is deprecated since API version 9. Use [Curves.stepsCurve](# curvesstepscurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - - -## Curves.cubicBezier(deprecated) - -cubicBezier(x1: number, y1: number, x2: number, y2: number): string - - -Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - - -## Curves.spring(deprecated) - -spring(velocity: number, mass: number, stiffness: number, damping: number): string - - -Constructs a spring curve object. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| -| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.| - - -## Curve - -| Name | Description | -| ------------------- | ---------------------------------------- | -| Linear | The animation speed keeps unchanged. | -| Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.| -| EaseIn | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.| -| EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.| -| EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.| -| FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).| -| LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).| -| FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0).| -| ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).| -| Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).| -| Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).| -| Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).| -| Friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0).| - - -## Example - -```ts -// xxx.ets -import Curves from '@ohos.curves' -@Entry -@Component -struct ImageComponent { - @State widthSize: number = 200 - @State heightSize: number = 200 - build() { - Column() { - Text() - .margin({top:100}) - .width(this.widthSize) - .height(this.heightSize) - .backgroundColor(Color.Red) - .onClick(()=> { - let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0); - this.widthSize = curve.interpolate(0.5) * this.widthSize; - this.heightSize = curve.interpolate(0.5) * this.heightSize; - }) - .animation({duration: 2000 , curve: Curves.stepsCurve(9, true)}) - }.width("100%").height("100%") - } -} -``` -![en-us_image_0000001212058456](figures/en-us_image_0000001212058456.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md b/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md deleted file mode 100644 index 34f1738c2085bd8c77e6c69f43845a37bbc98985..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md +++ /dev/null @@ -1,441 +0,0 @@ -# Matrix Transformation - -Matrix transformation enables you to rotate, scale, skew, or translate an image. - -> **NOTE** -> -> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```ts -import matrix4 from '@ohos.matrix4' -``` - - -## matrix4.init - -init(array: Array<number>): Matrix4Transit - - -Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------- | ---- | ------------------------------------------------------------ | -| array | Array<number> | Yes | A number array whose length is 16 (4 x 4). For details, see **array**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | 4x4 matrix object created based on the input parameter.| - -**array** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------------- | -| m00 | number | Yes | Scaling value of the x-axis. Defaults to **1** for the identity matrix. | -| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. | -| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. | -| m03 | number | Yes | Meaningless. | -| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. | -| m11 | number | Yes | Scaling value of the y-axis. Defaults to **1** for the identity matrix. | -| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. | -| m13 | number | Yes | Meaningless. | -| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. | -| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. | -| m22 | number | Yes | Scaling value of the z-axis. Defaults to **1** for the identity matrix. | -| m23 | number | Yes | Meaningless. | -| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the identity matrix.| -| m31 | number | Yes | Translation value of the y-axis, in px. Defaults to **0** for the identity matrix.| -| m32 | number | Yes | Translation value of the z-axis, in px. Defaults to **0** for the identity matrix.| -| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. | - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// Create a 4x4 matrix. -let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix) - } - } -} -``` - - -## matrix4.identity - -identity(): Matrix4Transit - - -Matrix initialization function. Can return an identity matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------- | -| Matrix4Transit | Identity matrix object.| - -**Example** - -```ts -// The effect of matrix 1 is the same as that of matrix 2. -import matrix4 from '@ohos.matrix4' -let matrix1 = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -let matrix2 = matrix4.identity() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix1) - Image($r("app.media.zh")) - .width("40%") - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -## matrix4.copy - -copy(): Matrix4Transit - - -Matrix copy function, which is used to copy the current matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------------- | -| Matrix4Transit | Copy object of the current matrix.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = Matrix4.identity().translate({x:100}) - private matrix2 = this.matrix1.copy().scale({x:2}) - - build() { - Column() { - Image($r("app.media.bg1")) - .width("40%") - .height(100) - .transform(this.matrix1) - Image($r("app.media.bg2")) - .width("40%") - .height(100) - .margin({top:50}) - .transform(this.matrix2) - } - } -} -``` - -![en-us_image_0000001256858419](figures/en-us_image_0000001256858419.png) - - -## Matrix4 - - -### combine - -combine(matrix: Matrix4): Matrix4Transit - - -Matrix overlay function, which is used to overlay the effects of two matrices to generate a new matrix object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------ | -| matrix | Matrix4 | Yes | Matrix object to be overlaid.| - -**Return value** - -| Type | Description | -| -------------- | ------------------ | -| Matrix4Transit | Object after matrix overlay.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:200}).copy() - private matrix2 = matrix4.identity().scale({x:2}).copy() - - build() { - Column() { - // Before matrix transformation - Image($r("app.media.icon")) - .width("40%") - .height(100) - .margin({top:50}) - // Translate the x-axis by 200px, and then scale down the x-axis twice. - Image($r("app.media.icon")) - .transform(this.matrix1.combine(this.matrix2)) - .width("40%") - .height(100) - .margin({top:50}) - } - } -} -``` - -![en-us_image_0000001212378428](figures/en-us_image_0000001212378428.png) - - -### invert - -invert(): Matrix4Transit - - -Matrix inverse function. Can return an inverse matrix of the current matrix object, that is, get an opposite effect. - -**Return value** - -| Type | Description | -| -------------- | ---------------------- | -| Matrix4Transit | Inverse matrix object of the current matrix.| - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x). -let matrix1 = matrix4.identity().scale({x:2}) -let matrix2 = matrix1.invert() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width(200) - .height(100) - .transform(matrix1) - .margin({ top: 100 }) - Image($r("app.media.zh")) - .width(200) - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -### translate - -translate({x?: number, y?: number, z?: number}): Matrix4Transit - - -Matrix translation function, which is used to add the translation effect to the x, y, and z axes of the current matrix. - -**Parameter** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------- | -| x | number | No | Translation distance of the x-axis, in px.
Default value: **0**| -| y | number | No | Translation distance of the y-axis, in px.
Default value: **0**| -| z | number | No | Translation distance of the z-axis, in px.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the translation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:100, y:200, z:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![en-us_image_0000001212058494](figures/en-us_image_0000001212058494.png) - - -### scale - -scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Matrix4Transit - - -Matrix scaling function, which is used to add the scaling effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | Scaling multiple of the x-axis.
Default value: **1** | -| y | number | No | Scaling multiple of the y-axis.
Default value: **1** | -| z | number | No | Scaling multiple of the z-axis.
Default value: **1** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the scaling effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![zh-cn_image_0000001219864131](figures/zh-cn_image_0000001219864131.png) - - -### rotate - -rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Matrix4Transit - - -Matrix rotation function, which is used to add the rotation effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | X coordinate of the rotation axis vector.
Default value: **1** | -| y | number | No | Y coordinate of the rotation axis vector.
Default value: **1** | -| z | number | No | Z coordinate of the rotation axis vector.
Default value: **1** | -| angle | number | No | Rotation angle.
Default value: **0** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the rotation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - }.width("100%").margin({top:50}) - } -} -``` - -![en-us_image_0000001211898504](figures/en-us_image_0000001211898504.png) - - -### transformPoint - -transformPoint(point: Point): Point - - -Matrix point transformation function, which is used to apply the current transformation effect to a coordinate point. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----- | ---- | ------------------ | -| point | Point | Yes | Point to be transformed.| - -**Return value** - -| Type | Description | -| ----- | ---------------- | -| Point | Point object after matrix transformation| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -import prompt from '@system.prompt' - -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().transformPoint([100, 10]) - - build() { - Column() { - Button("get Point") - .onClick(() => { - prompt.showToast({message:JSON.stringify(this.matrix1),duration:2000}) - }).backgroundColor(0x2788D9) - }.width("100%").padding(50) - } -} -``` - -![en-us_image_0000001212218464](figures/en-us_image_0000001212218464.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index 158a8f0395f635c7417de49579d1f9bdfa61ab8e..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+ diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 8fc5a51f8ce0dfa8f141d000348257dae7fddfd9..5b082bc803d6d82e93c273fc1ea9ba4ddfd25ce1 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -2,47 +2,46 @@ Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency. - > **NOTE** -> +> > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## APIs OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings) **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------- | ---------------------------------------- | ---- | ---- | ------------------------------ | -| width | number | Yes | - | Width of the offscreen canvas. | -| height | number | Yes | - | Height of the offscreen canvas. | -| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | - | See RenderingContextSettings.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------ | +| width | number | Yes | Width of the offscreen canvas. | +| height | number | Yes | Height of the offscreen canvas. | +| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | See RenderingContextSettings.| ## Attributes -| Name | Type | Description | -| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.
- When the type is **\**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineWidth](#linewidth) | number | Line width. | -| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
- Default value: **'butt'** | -| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
- Default value: **'miter'** | -| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
- Default value: **10** | -| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'** | -| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
**NOTE**
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
- Default value: **'left'** | -| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
- Default value: **'alphabetic'** | -| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | -| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
- Default value: **0.0** | -| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
- Default value: **'source-over'** | -| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
- Default value: **0.0** | -| [shadowColor](#shadowcolor) | string | Shadow color. | -| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | -| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
- Default value: **true** | -| imageSmoothingQuality | string | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**.
- Default value: **'low'** | +| Name | Type | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.
- When the type is **string**, this attribute indicates the color of the filling area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineWidth](#linewidth) | number | Line width. | +| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
- Default value: **'butt'**| +| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
- Default value: **'miter'**| +| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
- Default value: **10**| +| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'**| +| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
> **NOTE**
> In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
- Default value: **'left'**| +| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
- Default value: **'alphabetic'**| +| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | +| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
- Default value: **0.0**| +| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
- Default value: **'source-over'**| +| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
- Default value: **0.0**| +| [shadowColor](#shadowcolor) | string | Shadow color. | +| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | +| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
- Default value: **true**| > **NOTE** > @@ -574,8 +573,7 @@ struct ShadowColor { this.offContext.shadowColor = 'rgb(0,0,255)' this.offContext.fillStyle = 'rgb(255,0,0)' this.offContext.fillRect(30, 30, 100, 100) - var image = this.offContext.transferToImageBitmap -() + var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -769,6 +767,7 @@ Draws an outlined rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -815,6 +814,7 @@ Clears the content in a rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -823,8 +823,8 @@ Clears the content in a rectangle on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(0,0,500,500) - this.offContext.clearRect(20,20,150,100) + this.offContext.fillRect(20,20,200,200) + this.offContext.clearRect(30,30,150,100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -846,12 +846,12 @@ Draws filled text on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | --------------- | -| text | string | Yes | "" | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width allowed for the text.| +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | "" | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width allowed for the text. | **Example** @@ -863,6 +863,7 @@ Draws filled text on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -893,12 +894,12 @@ Draws a text stroke on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | --------------- | -| text | string | Yes | "" | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width of the text to be drawn.| +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | "" | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width of the text to be drawn. | **Example** @@ -910,6 +911,7 @@ Draws a text stroke on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -950,12 +952,12 @@ Returns a **TextMetrics** object used to obtain the width of specified text. | ----------- | ------- | | TextMetrics | **TextMetrics** object.| -**TextMetrics** +**TextMetrics** attributes -| Name | Type | Description | -| ----- | ------ | ------- | -| width | number | Width of the text.| -| height | number | Height of the text.| +| Name | Type | Description | +| ------------------------ | ------ | ---------------------------------------- | +| width | number | Width of the text. | +| height | number | Height of the text. | | actualBoundingBoxAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the bounding rectangle used to render the text. The current value is **0**.| | actualBoundingBoxDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the bounding rectangle used to render the text. The current value is **0**.| | actualBoundingBoxLeft | number | Distance parallel to the baseline from the alignment point determined by the **CanvasRenderingContext2D.textAlign** attribute to the left side of the bounding rectangle of the text. The current value is **0**.| @@ -978,6 +980,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1014,7 +1017,7 @@ Strokes a path. | path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.| **Example** - + ```ts // xxx.ets @Entry @@ -1023,6 +1026,7 @@ Strokes a path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1032,6 +1036,8 @@ Strokes a path. .onReady(() =>{ this.offContext.moveTo(25, 25) this.offContext.lineTo(25, 105) + this.offContext.lineTo(75, 105) + this.offContext.lineTo(75, 25) this.offContext.strokeStyle = 'rgb(0,0,255)' this.offContext.stroke() var image = this.offContext.transferToImageBitmap() @@ -1063,6 +1069,7 @@ Creates a drawing path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1112,6 +1119,7 @@ Moves a drawing path to a target position on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1159,6 +1167,7 @@ Connects the current point to a target position using a straight line. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1199,6 +1208,7 @@ Draws a closed path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1240,9 +1250,9 @@ Creates a pattern for image filling based on a specified source image and repeti **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| +| Type | Description | +| ------------------------------- | ----------------------- | +| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| **Example** @@ -1255,6 +1265,7 @@ Creates a pattern for image filling based on a specified source image and repeti private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1305,6 +1316,7 @@ Draws a cubic bezier curve on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1354,6 +1366,7 @@ Draws a quadratic curve on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1386,13 +1399,13 @@ Draws an arc on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------------- | ------- | ---- | ----- | ---------- | -| x | number | Yes | 0 | X-coordinate of the center point of the arc.| -| y | number | Yes | 0 | Y-coordinate of the center point of the arc.| -| radius | number | Yes | 0 | Radius of the arc. | -| startAngle | number | Yes | 0 | Start radian of the arc. | -| endAngle | number | Yes | 0 | End radian of the arc. | +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ----- | ---------- | +| x | number | Yes | 0 | X-coordinate of the center point of the arc.| +| y | number | Yes | 0 | Y-coordinate of the center point of the arc.| +| radius | number | Yes | 0 | Radius of the arc. | +| startAngle | number | Yes | 0 | Start radian of the arc. | +| endAngle | number | Yes | 0 | End radian of the arc. | | counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.| **Example** @@ -1405,6 +1418,7 @@ Draws an arc on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1454,6 +1468,7 @@ Draws an arc based on the radius and points on the arc. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1485,15 +1500,15 @@ Draws an ellipse in the specified rectangular region on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------------- | ------- | ---- | ----- | ----------------- | -| x | number | Yes | 0 | X-coordinate of the ellipse center. | -| y | number | Yes | 0 | Y-coordinate of the ellipse center. | -| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | -| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | -| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | -| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| -| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ----- | ----------------- | +| x | number | Yes | 0 | X-coordinate of the ellipse center. | +| y | number | Yes | 0 | Y-coordinate of the ellipse center. | +| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | +| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | +| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | +| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| +| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| | counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. | **Example** @@ -1514,7 +1529,7 @@ Draws an ellipse in the specified rectangular region on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.beginPath() - this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -1537,12 +1552,12 @@ Creates a rectangle on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ------------- | -| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| -| w | number | Yes | 0 | Width of the rectangle. | -| h | number | Yes | 0 | Height of the rectangle. | +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | ------------- | +| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| +| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| +| w | number | Yes | 0 | Width of the rectangle. | +| h | number | Yes | 0 | Height of the rectangle. | **Example** @@ -1554,6 +1569,7 @@ Creates a rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1578,11 +1594,15 @@ Creates a rectangle on the canvas. ### fill -fill(): void +fill(fillRule?: CanvasFillRule): void Fills the area inside a closed path on the canvas. - **Example** +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| ```ts // xxx.ets @@ -1592,6 +1612,7 @@ Fills the area inside a closed path on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1614,12 +1635,73 @@ Fills the area inside a closed path on the canvas. ![en-us_image_0000001256858421](figures/en-us_image_0000001256858421.png) +fill(path: Path2D, fillRule?: CanvasFillRule): void + +Fills the area inside a closed path on the canvas. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | Yes | | A **Path2D** path to fill. | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| + + +**Example** + +```ts +// xxx.ets +@Entry +@Component +struct Fill { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.moveTo(30, 90); + region.lineTo(110, 20); + region.lineTo(240, 130); + region.lineTo(60, 130); + region.lineTo(190, 20); + region.lineTo(270, 90); + region.closePath(); + // Fill path + this.offContext.fillStyle = 'green'; + this.offContext.fill(region, "evenodd"); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} +``` + + ![en-us_image_000000127777775](figures/en-us_image_000000127777775.png) + + + ### clip -clip(): void +clip(fillRule?: CanvasFillRule): void Sets the current path to a clipping path. +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| + **Example** ```ts @@ -1630,6 +1712,7 @@ Sets the current path to a clipping path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1637,11 +1720,11 @@ Sets the current path to a clipping path. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rect(0, 0, 200, 200) + this.offContext.rect(0, 0, 100, 200) this.offContext.stroke() this.offContext.clip() this.offContext.fillStyle = "rgb(255,0,0)" - this.offContext.fillRect(0, 0, 150, 150) + this.offContext.fillRect(0, 0, 200, 200) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1655,6 +1738,89 @@ Sets the current path to a clipping path. ![en-us_image_0000001257058441](figures/en-us_image_0000001257058441.png) +clip(path:Path2D, fillRule?: CanvasFillRule): void + +Sets a closed path to a clipping path. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | Yes | | A **Path2D** path to clip.| +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| + + **Example** + + ```ts + // xxx.ets +@Entry +@Component +struct Clip { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.rect(80,10,20,130); + region.rect(40,50,100,50); + this.offContext.clip(region,"evenodd") + this.offContext.fillStyle = "rgb(255,0,0)" + this.offContext.fillRect(0, 0, 600, 600) + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777779](figures/en-us_image_000000127777779.png) + + + +### filter + +filter(filter: string): void + +Sets a filter for the image on the canvas. This API is a void API. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ------ | ------ | ---- | ---- | ------------ | +| filter | string | Yes | - | Functions that accept various filter effects.| + + +### getTransform + +getTransform(): Matrix2D + +Obtains the current transformation matrix being applied to the context. This API is a void API. + + +### resetTransform + +resetTransform(): void + +Resets the current transform to the identity matrix. This API is a void API. + + +### direction + +direction(direction: CanvasDirection): void + +Sets the text direction for drawing text. This API is a void API. + + ### rotate rotate(angle: number): void @@ -1663,8 +1829,8 @@ Rotates a canvas clockwise around its coordinate axes. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | +| Name | Type | Mandatory | Default Value | Description | +| ----- | ------ | ---- | ---- | ---------------------------------------- | | angle | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.| **Example** @@ -1677,6 +1843,7 @@ Rotates a canvas clockwise around its coordinate axes. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1722,6 +1889,7 @@ Scales the canvas based on scale factors. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1729,9 +1897,10 @@ Scales the canvas based on scale factors. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.lineWidth = 3 + this.offContext.strokeRect(30, 30, 50, 50) this.offContext.scale(2, 2) // Scale to 200% - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.strokeRect(30, 30, 50, 50) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1761,14 +1930,14 @@ Defines a transformation matrix. To transform a graph, you only need to set para **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---------- | ------ | ---- | ---- | -------- | -| a | number | Yes | 0 |X-axis scale.| -| b | number | Yes | 0 |X-axis skew.| -| c | number | Yes | 0 |Y-axis skew.| -| d | number | Yes | 0 |Y-axis scale.| -| e | number | Yes | 0 |X-axis translation.| -| f | number | Yes | 0 |Y-axis translation.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | -------------------- | +| a | number | Yes | 0 | X-axis scale. | +| b | number | Yes | 0 | X-axis skew. | +| c | number | Yes | 0 | Y-axis skew. | +| d | number | Yes | 0 | Y-axis scale. | +| e | number | Yes | 0 | X-axis translation.| +| f | number | Yes | 0 | Y-axis translation.| **Example** @@ -1780,6 +1949,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1812,18 +1982,18 @@ Defines a transformation matrix. To transform a graph, you only need to set para setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void -Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. +Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | -| ---------- | ------ | ---- | ---- | -------- | -| a | number | Yes | 0 |X-axis scale.| -| b | number | Yes | 0 |X-axis skew.| -| c | number | Yes | 0 |Y-axis skew.| -| d | number | Yes | 0 |Y-axis scale.| -| e | number | Yes | 0 |X-axis translation.| -| f | number | Yes | 0 |Y-axis translation.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | -------------------- | +| a | number | Yes | 0 | X-axis scale. | +| b | number | Yes | 0 | X-axis skew. | +| c | number | Yes | 0 | Y-axis skew. | +| d | number | Yes | 0 | Y-axis scale. | +| e | number | Yes | 0 | X-axis translation.| +| f | number | Yes | 0 | Y-axis translation.| **Example** @@ -1835,6 +2005,7 @@ Resets the existing transformation matrix and creates a new transformation matri private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1857,8 +2028,10 @@ Resets the existing transformation matrix and creates a new transformation matri } ``` - ![zh-cn_image_0000001193872526](figures/zh-cn_image_0000001193872526.png) + ![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png) + +### translate ### translate @@ -1868,7 +2041,7 @@ Moves the origin of the coordinate system. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | -------- | | x | number | Yes | 0 | X-axis translation.| | y | number | Yes | 0 | Y-axis translation.| @@ -1883,6 +2056,7 @@ Moves the origin of the coordinate system. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1903,7 +2077,7 @@ Moves the origin of the coordinate system. } ``` - ![en-us_image_0000001256978373](figures/en-us_image_0000001256978373.png) + ![en-us_image_0000001238832413](figures/en-us_image_0000001238832413.png) ### drawImage @@ -1918,17 +2092,17 @@ Draws an image on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------- | ---------------------------------------- | ---- | ---- | -------------------- | -| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.| -| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image.| -| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image.| -| sw | number | No | 0 | Target width to crop the source image. | -| sh | number | No | 0 | Target height to crop the source image. | -| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | -| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas.| -| dw | number | No | 0 | Width of the drawing area. | -| dh | number | No | 0 | Height of the drawing area. | +| Name | Type | Mandatory | Default Value | Description | +| ----- | ---------------------------------------- | ---- | ---- | ----------------------------- | +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.| +| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sw | number | No | 0 | Target width to crop the source image. | +| sh | number | No | 0 | Target height to crop the source image. | +| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | +| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. | +| dw | number | No | 0 | Width of the drawing area. | +| dh | number | No | 0 | Height of the drawing area. | **Example** @@ -1937,7 +2111,7 @@ Draws an image on the canvas. // xxx.ets @Entry @Component - struct Index { + struct DrawImage { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") @@ -1967,33 +2141,31 @@ Draws an image on the canvas. createImageData(sw: number, sh: number): ImageData -Creates an **ImageData** object based on the width and height. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ------------- | -| sw | number | Yes | 0 | Width of the **ImageData** object.| -| sh | number | Yes | 0 | Height of the **ImageData** object.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | ------------- | +| sw | number | Yes | 0 | Width of the **ImageData** object.| +| sh | number | Yes | 0 | Height of the **ImageData** object.| -### createImageData - createImageData(imageData: ImageData): ImageData -Creates an **ImageData** object based on the given existing **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object by copying an existing **ImageData** object. **Parameters** | Name | Type | Mandatory | Default Value | Description | | --------- | ---------------------------------------- | ---- | ---- | ---------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy.| +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object to copy.| **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| Type | Description | +| ---------------------------------------- | ------------- | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| ### getPixelMap @@ -2003,29 +2175,29 @@ Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created wi **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| sx | number | Yes| 0 | X-coordinate of the upper left corner of the output area.| -| sy | number | Yes| 0 | Y-coordinate of the upper left corner of the output area.| -| sw | number | Yes| 0 | Width of the output area.| -| sh | number | Yes| 0 | Height of the output area.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | --------------- | +| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| +| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| +| sw | number | Yes | 0 | Width of the output area. | +| sh | number | Yes | 0 | Height of the output area. | **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.| +| Type | Description | +| ---------------------------------------- | ------------ | +| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.| ### getImageData getImageData(sx: number, sy: number, sw: number, sh: number): ImageData -Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas. +Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | --------------- | | sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| | sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| @@ -2034,9 +2206,44 @@ Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| Type | Description | +| ---------------------------------------- | ------------- | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| + + +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct GetImageData { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.drawImage(this.img,0,0,130,130); + var imagedata = this.offContext.getImageData(50,50,130,130); + this.offContext.putImageData(imagedata,150,150); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) ### putImageData @@ -2045,11 +2252,11 @@ putImageData(imageData: Object, dx: number, dy: number): void putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth?: number, dirtyHeight: number): void -Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular area on the canvas. +Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ----------- | ------ | ---- | ------------ | ----------------------------- | | imagedata | Object | Yes | null | **ImageData** object with pixels to put onto the canvas. | | dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | @@ -2104,8 +2311,8 @@ Sets the dash line style. **Parameters** -| Parameter | Type | Description | -| -------- | ----- | -------------------- | +| Name | Type | Description | +| -------- | -------- | ------------------- | | segments | number[] | An array of numbers that specify distances to alternately draw a line and a gap.| **Example** @@ -2137,7 +2344,7 @@ struct SetLineDash { } } ``` - ![zh-cn_image_000000127777772](figures/zh-cn_image_000000127777772.png) + ![en-us_image_000000127777772](figures/en-us_image_000000127777772.png) ### getLineDash @@ -2148,29 +2355,37 @@ Obtains the dash line style. **Return value** -| Type | Description | -| ----- | ------------------------ | +| Type | Description | +| -------- | ------------------------ | | number[] | An array describing the interval of alternate line segments and length of spacing.| **Example** ```ts // xxx.ets - @Entry - @Component - struct GetLineDash { +@Entry +@Component +struct OffscreenCanvasGetLineDash { + @State message: string = 'Hello World' private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + console.error('before getlinedash clicked') + let res = this.offContext.getLineDash() + console.error(JSON.stringify(res)) + }) Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) + .onReady(() => { this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.setLineDash([10,20]) this.offContext.stroke(); @@ -2180,53 +2395,14 @@ Obtains the dash line style. }) } .width('100%') - .height('100%') } + .height('100%') } +} ``` +![en-us_image_000000127777778](figures/en-us_image_000000127777778.png) -### transferFromImageBitmap - -transferFromImageBitmap(bitmap: ImageBitmap): void - -Displays the specified **ImageBitmap** object. - -**Parameters** - -| Parameters | Type | Description | -| ------ | ----------- | ------------------ | -| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct GetLineDash { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.fillRect(0, 0, 200, 200) - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') - } - } - ``` - ![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png) ### toDataURL @@ -2250,7 +2426,7 @@ Generates a URL containing image display information. **Example** ```ts - // xxx.ets +// xxx.ets @Entry @Component struct ToDataURL { @@ -2275,6 +2451,19 @@ struct ToDataURL { ``` +### imageSmoothingQuality + +imageSmoothingQuality(quality: imageSmoothingQuality) + +Sets the quality of image smoothing. This API is a void API. + + **Parameters** + +| Name | Type | Description | +| ------- | --------------------- | ---------------------------------------- | +| quality | imageSmoothingQuality | Quality of image smoothing. The value can be **'low'**, **'medium'**,or **'high'**.| + + ### transferToImageBitmap transferToImageBitmap(): ImageBitmap @@ -2285,7 +2474,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O | Type | Description | | ---------------------------------------- | --------------- | -| [ImageData](ts-components-canvas-imagebitmap.md)| Pixel data rendered on the **OffscreenCanvas**.| +| [ImageBitmap](ts-components-canvas-imagebitmap.md) | Pixel data rendered on the **OffscreenCanvas**.| **Example** @@ -2294,10 +2483,11 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O // xxx.ets @Entry @Component - struct CanvasExample { + struct PutImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2305,7 +2495,14 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.restore() + var imageData = this.offContext.createImageData(100, 100) + for (var i = 0; i < imageData.data.length; i += 4) { + imageData.data[i + 0] = 255 + imageData.data[i + 1] = 0 + imageData.data[i + 2] = 255 + imageData.data[i + 3] = 255 + } + this.offContext.putImageData(imageData, 10, 10) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2315,6 +2512,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O } } ``` +![en-us_image_0000001238952387](figures/en-us_image_0000001238952387.png) ### restore @@ -2326,29 +2524,35 @@ Restores the saved drawing context. ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.restore() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) } + .width('100%') + .height('100%') } +} ``` +![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### save @@ -2361,29 +2565,35 @@ Saves the current drawing context. ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.save() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) }) - } - .width('100%') - .height('100%') } + .width('100%') + .height('100%') } +} ``` +![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### createLinearGradient diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-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-image-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index c02876ce0f77ca67db58378aa68dc044846dbc75..c82ec4fab433b607cf344864a1126ac94332e89c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -78,4 +78,4 @@ struct ImageEffectsExample { } ``` -image-effect +![](figures/image-effect.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-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-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-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/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/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 2b4efca72f4786729d4f11234febd406778bc266..e4838da489a5d5bb3ac3651885c9d456ed7322eb 100644 --- a/en/application-dev/ui/Readme-EN.md +++ b/en/application-dev/ui/Readme-EN.md @@ -11,49 +11,11 @@ - [Resource File Categories](ui-ts-basic-resource-file-categories.md) - [Resource Access](ts-resource-access.md) - [Pixel Units](ts-pixel-units.md) - - Declarative Syntax - - [About Usage of UI Description Specifications](ts-syntax-intro.md) - - About General UI Description Specifications - - [Basic Concepts](ts-general-ui-concepts.md) - - Declarative UI Description Specifications - - [Configuration Without Parameters](ts-parameterless-configuration.md) - - [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md) - - [Attribute Configuration](ts-attribution-configuration.md) - - [Event Configuration](ts-event-configuration.md) - - [Child Component Configuration](ts-child-component-configuration.md) - - Componentization - - [@Component](ts-component-based-component.md) - - [@Entry](ts-component-based-entry.md) - - [@Preview](ts-component-based-preview.md) - - [@Builder](ts-component-based-builder.md) - - [@Extend](ts-component-based-extend.md) - - [@CustomDialog](ts-component-based-customdialog.md) - - [@Styles](ts-component-based-styles.md) - - About UI State Management - - [Basic Concepts](ts-ui-state-mgmt-concepts.md) - - Managing Component States - - [@State](ts-component-states-state.md) - - [@Prop](ts-component-states-prop.md) - - [@Link](ts-component-states-link.md) - - Managing Application States - - [AppStorage](ts-application-states-appstorage.md) - - [LocalStorage](ui-ts-local-storage.md) - - [PersistentStorage](ts-application-states-apis-persistentstorage.md) - - [Environment](ts-application-states-apis-environment.md) - - Managing Other States - - [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md) - - [@Consume and @Provide](ts-other-states-consume-provide.md) - - [@Watch](ts-other-states-watch.md) - - Rendering Control Syntax - - [if/else](ts-rending-control-syntax-if-else.md) - - [ForEach](ts-rending-control-syntax-foreach.md) - - [LazyForEach](ts-rending-control-syntax-lazyforeach.md) - - About Componentization - - [build Function](ts-function-build.md) + + - Componentization - [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md) - [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md) - - [Examples: Component Creation and Re-initialization](ts-component-creation-re-initialization.md) - - [About Syntactic Sugar](ts-syntactic-sugar.md) + - [Component Creation and Re-initialization](ts-component-creation-re-initialization.md) - Common Component Development Guidelines - [Button](ui-ts-basic-components-button.md) - [Web](ui-ts-components-web.md) diff --git a/en/application-dev/ui/arkui-overview.md b/en/application-dev/ui/arkui-overview.md index 43bff6f16355673a8bc4b027680e427b9801d4d3..5859e248d019b64d8e78886d8d4b5c518acf39b9 100644 --- a/en/application-dev/ui/arkui-overview.md +++ b/en/application-dev/ui/arkui-overview.md @@ -21,7 +21,7 @@ ArkUI is a UI development framework that provides what you'll need to develop ap - Drawing: ArkUI offers advanced drawing capabilities that allow you to draw custom shapes with a range of editors, from images to fill colors and texts. - Interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability. - Platform API channel: ArkUI provides an API extension mechanism through which platform capabilities are encapsulated to produce JavaScript APIs in a unified style. -- Two development paradigms: ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice. +- Two development paradigms: ArkUI comes with two development paradigms: eTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). You can choose whichever development paradigm that aligns with your practice. | Development Paradigm | Description | Applicable To | Intended Audience | | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/ui/ts-application-states-apis-environment.md b/en/application-dev/ui/ts-application-states-apis-environment.md deleted file mode 100644 index 9da95fc0b83e5cb259e2233275075f734252e953..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-apis-environment.md +++ /dev/null @@ -1,34 +0,0 @@ -# Environment - - -Environment is a singleton object created by the framework when the application is started. It provides the AppStorage with a series of environment state attributes required by the application. These attributes describe the device environment where the application runs. Environment and its attributes are immutable, and all attribute values are of the simple type. The following example shows how to obtain the semantic environment from Environment: - - -```ts -Environment.EnvProp("accessibilityEnabled", "default"); -var enable = AppStorage.Get("accessibilityEnabled"); -``` - - -accessibilityEnabled is the default system variable identifier provided by Environment. You need to bind the corresponding system attribute to the AppStorage. Then, you can use the methods or decorators in the AppStorage to access the corresponding system attribute data. - - -## Environment APIs - -| key | Parameter | Return Value | Description | -| -------- | -------- | -------- | -------- | -| EnvProp | key: string,
defaultValue: any | boolean | Binds this system attribute to the AppStorage. You are advised to use this API during application startup. If the attribute already exists in the AppStorage, false is returned. Do not use the variables in the AppStorage. Instead, call this method to bind environment variables. | -| EnvProps | keys: {
key: string,
defaultValue: any
}[] | void | Associates this system item array with the AppStorage. | -| Keys | Array<string> | number | Returns the associated system item array. | - - -## Built-in Environment Variables - -| key | Type | Description | -| -------- | -------- | -------- | -| accessibilityEnabled | boolean | Whether to enable accessibility. | -| colorMode | ColorMode | Color mode. The options are as follows:
- **ColorMode.LIGHT**: light mode.
- **ColorMode.DARK**: dark mode. | -| fontScale | number | Font scale. The value range is [0.85, 1.45]. | -| fontWeightScale | number | Font weight scale. The value range is [0.6, 1.6]. | -| layoutDirection | LayoutDirection | Layout direction. The options are as follows:
- **LayoutDirection.LTR**: The direction is from left to right.
- **LayoutDirection.RTL**: The direction is from right to left. | -| languageCode | string | Current system language. The value is in lowercase, for example, zh. | diff --git a/en/application-dev/ui/ts-application-states-apis-persistentstorage.md b/en/application-dev/ui/ts-application-states-apis-persistentstorage.md deleted file mode 100644 index 8df5e76e2855c5f5d211aa35d87f54d19f5ce352..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-apis-persistentstorage.md +++ /dev/null @@ -1,48 +0,0 @@ -# PersistentStorage - - -ArkUI provides some static methods in the PersistentStorage class for managing persistent data of applications. Persistent data with specific tags can be linked to the AppStorage, and then the persistent data can be accessed through the AppStorage APIs. Alternatively, the @StorageLink decorator can be used to access the variable of the specific key. - - -| Name | Type | Return Value | Definition | -| -------- | -------- | -------- | -------- | -| PersistProp | key : string
defaultValue: T | void | Changes the associated named attribute to persistent data in the AppStorage. The value overwriting sequence is as follows:
- If the attribute exists in the AppStorage, use it to overwrite the value in Persistent.
- If Persistent contains the specified attribute, use the attribute value in Persistent.
- If the preceding conditions are not met, use defaultValue. The values null and undefined are not supported. | -| DeleteProp | key: string | void | Cancels two-way binding. The value of this attribute will be deleted from the persistent storage. | -| PersistProps | keys: {
key: string,
defaultValue: any
}[] | void | Associates multiple named attribute bindings. | -| Keys | void | Array <string> | Returns the flags of all persistent attributes. | - - -> **NOTE** -> -> - When using **PersistProp**, ensure that the input key exists in the AppStorage. -> -> - **DeleteProp** takes effect only for the data that has been linked during the current startup. - - -```ts -// xxx.ets -PersistentStorage.PersistProp("highScore", "0"); - -@Entry -@Component -struct PersistentComponent { - @StorageLink('highScore') highScore: string = '0' - @State currentScore: number = 0 - build() { - Column() { - if (this.currentScore === Number(this.highScore)) { - Text(`new highScore : ${this.highScore}`) - } - Button() { - Text(`goal!, currentScore : ${this.currentScore}`) - .fontSize(10) - }.onClick(() => { - this.currentScore++ - if (this.currentScore > Number(this.highScore)) { - this.highScore = this.currentScore.toString() - } - }) - } - } -} -``` diff --git a/en/application-dev/ui/ts-application-states-appstorage.md b/en/application-dev/ui/ts-application-states-appstorage.md deleted file mode 100644 index 5877f75ca55ad03cafb78eda50c0b26475f3033e..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-appstorage.md +++ /dev/null @@ -1,89 +0,0 @@ -# AppStorage - - -AppStorage is a singleton object in an application, which is created by the UI framework when the application is started and destroyed when the application exits. It is used to provide central storage for changing state attributes of an application. AppStorage contains all the state attributes that need to be accessed throughout the application. The AppStorage retains all attributes and their values as long as the application remains running, and the attribute values can be accessed through unique key values. - - -The UI component can synchronize the application state data with the AppStorage through the decorators. The application service logic can also be implemented by accessing the AppStorage through APIs. - - -The selection state attribute of the AppStorage can be synchronized with different data sources or data sinks. These data sources and data sinks can be local or remote devices and provide different functions, such as data persistence. Such data sources and data sinks can be implemented independently of the UI in the service logic. - - -By default, the attributes in the AppStorage are changeable. If needed, AppStorage can also use immutable (read-only) attributes. - - -## AppStorage APIs - -| Name | Type | Return Value | Definition | -| -------- | -------- | -------- | -------- | -| SetAndLink | key: string,
defaultValue: T | @Link | Works in a way similar to the Link API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Link instance corresponding to the default value is created and returned. | -| Set | key: string,
newValue: T | void | Replaces the value of a saved key. | -| Link | key: string | @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the AppStorage, and attribute changes made through the AppStorage will be synchronized to the variable or component. If the attribute with this key does not exist or is read-only, undefined is returned. | -| SetAndProp | propName: string,
defaultValue: S | @Prop | Works in a way similar to the Prop API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Prop instance corresponding to the default value is created and returned. | -| Prop | key: string | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the AppStorage will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the AppStorage. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, undefined is returned.
**NOTE**
The attribute value used in the prop method must be of a simple type. | -| SetOrCreate | key: string,
newValue: T | boolean | If an attribute that has the same name as the specified key exists: replaces the value of the attribute and returns true when the attribute can be modified; retains the original value of the attribute and returns false otherwise.
If an attribute that has the same name as the specified key does not exist: creates an attribute whose key is key and value is newValue. The values null and undefined are not supported. | -| Get | key: string | T or undefined | Obtains the value of the specified key. | -| Has | propName: string | boolean | Checks whether the attribute corresponding to the specified key value exists. | -| Keys | void | array<string> | Returns an array of strings containing all keys. | -| Delete | key: string | boolean | Deletes the key-value pair for the specified key. Returns true if the key-value pair exists and is successfully deleted; returns false otherwise. | -| Clear | void | boolean | Deletes all attributes. If any of the attributes is being referenced by a state variable, false is returned. | -| IsMutable | key: string | boolean | Specifies whether the attribute exists and can be changed. | - - -## Synchronization Between AppStorage and Components - -In [Managing Component States](ts-component-states-state.md), we have defined how to synchronize the state variables of child components with the @State decorated variables in the parent component or ancestor component, including @Prop, @Link, and @Consume. - -In this section, we'll describe how to synchronize component variables with the AppStorage through the @StorageLink and @StorageProp decorators. - - -### @StorageLink Decorator - -Two-way data binding can be established between components and the AppStorage through state variables decorated by @StorageLink(_key_). Wherein, key is the attribute key value in the AppStorage. When a component containing the @StorageLink decorated variable is created, the variable is initialized using the value in the AppStorage. Changes made to this variable in the component will be first synchronized to the AppStorage, and then to other bound instances, such as PersistentStorage or other bound UI components. - - -### @StorageProp Decorator - -One-way data binding can be established between components and the AppStorage through state variables decorated by @StorageProp(_key_). Wherein, key is the attribute key value in the AppStorage. When a component containing the @StorageProp decorated variable is created, the variable is initialized using the value in the AppStorage. Changes made to the value in the AppStorage will cause the bound UI component to update the state. - - -## Example - - -```ts -// xxx.ets - -@Entry -@Component -struct ComponentA { - @StorageLink('varA') varA: number = 2 - @StorageProp('languageCode') lang: string = 'en' - private label: string = 'count' - - aboutToAppear() { - this.label = (this.lang === 'en') ? 'Number' : 'Count' - } - - build() { - Row({ space: 20 }) { - - Button(`${this.label}: ${this.varA}`) - .onClick(() => { - AppStorage.Set('varA', AppStorage.Get('varA') + 1) - }) - Button(`lang: ${this.lang}`) - .onClick(() => { - if (this.lang === 'zh') { - AppStorage.Set('languageCode', 'en') - } else { - AppStorage.Set('languageCode', 'en') - } - this.label = (this.lang === 'en') ? 'Number' : 'Count' - }) - } - } -} -``` - -Each time the user clicks the **Count** button, the value of **this.varA** will increase by 1. This variable is synchronized with varA in the AppStorage. Each time the user clicks the language icon, the value of **languageCode** in the AppStorage will be changed, and the change will be synchronized to the **this.lang** variable. diff --git a/en/application-dev/ui/ts-attribution-configuration.md b/en/application-dev/ui/ts-attribution-configuration.md deleted file mode 100644 index 70d85aff0d3bb3a9b418753655ea33480bf681ff..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-attribution-configuration.md +++ /dev/null @@ -1,44 +0,0 @@ -# Attribute Configuration - - -Use attribute methods to configure component attributes. An attribute method follows the corresponding component and is bound to the component using the "." operator. - - -- The following is an example of configuring the font size attribute of the Text component: - - ```ts - Text('123') - .fontSize(12) - ``` - - -- Use the "." operator to implement chain call to configure multiple attributes at the same time, as shown below: - - ```ts - Image('a.jpg') - .alt('error.jpg') - .width(100) - .height(100) - ``` - - -- In addition to constants, you can also pass variables or expressions, as shown below: - - ```ts - // Size, count, and offset are private variables defined in the component. - Text('hello') - .fontSize(this.size) - Image('a.jpg') - .width(this.count % 2 === 0 ? 100 : 200) - .height(this.offset + 100) - ``` - - -- For attributes of preset components, the framework also provides some predefined enumeration types, which you can pass as parameters to methods. Enumeration types must meet the parameter type requirements on the enumeration type definitions for specific attributes. You can configure the font color and weight attributes of the Text component as follows: - - ```ts - Text('hello') - .fontSize(20) - .fontColor(Color.Red) - .fontWeight(FontWeight.Bold) - ``` diff --git a/en/application-dev/ui/ts-child-component-configuration.md b/en/application-dev/ui/ts-child-component-configuration.md deleted file mode 100644 index c2fe0c68c3b49e09091be56505cae0bea9e370fb..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-child-component-configuration.md +++ /dev/null @@ -1,49 +0,0 @@ -# Child Component Configuration - - -For a component that supports child components, for example, a container component, add the UI descriptions of the child components inside "{ ... }". The **\**, **\**, **\**, **\ -
- ``` + .height('100%') + } +} +``` ## 相关实例 diff --git a/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md index d31a74e423230d965ccda41153480ae2348f945f..a7da0fe1e9b46e5ccb379677a57e0da65cad36f7 100644 --- a/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md +++ b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md @@ -1,3 +1,12 @@ # 后台代理提醒概述 -开发者在应用开发时,可以调用后台代理提醒类ReminderRequest去创建定时提醒,包括倒计时、日历、闹钟三种提醒类型。使用后台代理提醒能力后,应用可以被冻结或退出,计时和弹出提醒的功能将被后台系统服务代理。 +OpenHarmony设计了相关的后台活动规范。三方应用退后台后如果没有执行相关的后台任务,会被挂起。而对于某些应用,可能需要在某些指定的时刻,处理一些工作。如购物类应用,可能需要在某些时间点,提醒用户有抢购活动可以参加。此类功能通常的实现是应用使用定时器,在时间达到后,由系统拉起应用,执行相关的任务。但是给应用开放了定时器的功能,可能会造成这个机制被滥用,导致后台被挂起的应用频繁地用定时器唤醒。为了避免恶意的后台活动,同时满足应用的业务诉求,设计了后台代理提醒功能。 +开发者在应用开发时,使用后台代理提醒能力后,应用可以被挂起或退出,计时和弹出提醒的功能将被后台系统服务代理。避免的应用被频繁唤醒的问题,有助于降低功耗。 + +## 提醒实例类型 + +- **倒计时类型**:基于倒计时的提醒功能,适用于短时的计时提醒业务。 + +- **日历类型**:基于日历的提醒功能,适用于较长时间的提醒业务。 + +- **闹钟类型**:基于时钟的提醒功能,应用可以使用此功能,实现闹钟相关的业务。 diff --git a/zh-cn/application-dev/task-management/background-task-dev-guide.md b/zh-cn/application-dev/task-management/background-task-dev-guide.md deleted file mode 100644 index fd4d3c3948b6ed69680c9294b10bb1838654b35f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/background-task-dev-guide.md +++ /dev/null @@ -1,582 +0,0 @@ -# 后台任务开发指导 - -## 场景介绍 - -应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。如果应用需要更加灵活的配置,可以申请能效资源。常见的使用能效资源的场景有:1.应用保证自己在一个时间段内不被挂起,直到任务完成;2.应用处于挂起状态时仍然需要系统的资源,例如闹钟需要计时器资源;3.延时任务需要不受到执行频率的限制,并且拥有更长的执行时间。 - -在挂起时如果需要单独的某种资源不被代理或者需要更长的延时任务执行时间,可以申请所需的能效资源。 - -## 短时任务 - -### 接口说明 - -**表1** 短时任务主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------------------- | -| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | 后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为180000,低电量时默认值为60000。 | -| getRemainingDelayTime(requestId: number): Promise<number> | 获取应用程序进入挂起状态前的剩余时间。
使用Promise形式返回。 | -| cancelSuspendDelay(requestId: number): void | 取消延迟挂起。 | - - -### 开发步骤 - - -1. 申请延迟挂起 - - ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - - let myReason = 'test requestSuspendDelay'; - let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspension delay will time out."); - }); - - var id = delayInfo.requestId; - console.info("requestId is: " + id); - ``` - - -2. 获取进入挂起前的剩余时间 - - ```js - backgroundTaskManager.getRemainingDelayTime(id).then( res => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - }).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); - }); - ``` - - -3. 取消延迟挂起 - - ```js - backgroundTaskManager.cancelSuspendDelay(id); - ``` - - -### 开发实例 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; -let myReason = 'test requestSuspendDelay'; - -// 申请延迟挂起 -let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspension delay will time out."); -}); - -// 打印延迟挂起信息 -var id = delayInfo.requestId; -var time = delayInfo.actualDelayTime; -console.info("The requestId is: " + id); -console.info("The actualDelayTime is: " + time); - -// 获取应用程序进入挂起状态前的剩余时间 -backgroundTaskManager.getRemainingDelayTime(id).then( res => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); -}).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); -}); - -// 取消延迟挂起 -backgroundTaskManager.cancelSuspendDelay(id); -``` - -## 长时任务 - -### 权限 - -ohos.permission.KEEP_BACKGROUND_RUNNING - -### 接口说明 - -**表2** 长时任务主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------- | -| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> | 服务启动后,向系统申请长时任务,使服务一直保持后台运行。 | -| stopBackgroundRunning(context: Context): Promise<void> | 停止后台长时任务的运行。 | - - -其中,wantAgent的信息详见([WantAgent](../reference/apis/js-apis-wantAgent.md)) - -**表3** 后台模式类型 - -| 参数名 | id值 | 描述 | 配置项 | -| ----------------------- | ---- | -------------- | --------------------- | -| DATA_TRANSFER | 1 | 数据传输 | dataTransfer | -| AUDIO_PLAYBACK | 2 | 音频播放 | audioPlayback | -| AUDIO_RECORDING | 3 | 录音 | audioRecording | -| LOCATION | 4 | 定位导航 | location | -| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | bluetoothInteraction | -| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | multiDeviceConnection | -| WIFI_INTERACTION | 7 | WLAN相关(系统保留) | wifiInteraction | -| VOIP | 8 | 音视频通话(系统保留) | voip | -| TASK_KEEPING | 9 | 计算任务(仅供特定设备使用) | taskKeeping | - - -### 开发步骤 - -基于FA模型: - -1. 新建Api Version 8的工程后,在工程目录中右键选择“new” -> “Ability” -> “Service Ability” 快速创建Service Ability组件。并在config.json文件中配置长时任务权限、后台模式类型,其中Ability类型为“service”。 - - ``` - "module": { - "package": "com.example.myapplication", - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // 后台模式类型 - "type": "service" // ability类型为service - } - ], - "reqPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 - } - ] - } - ``` - -2. 申请长时任务。 - - ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - import featureAbility from '@ohos.ability.featureAbility'; - import wantAgent from '@ohos.wantAgent'; - - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); - ``` - -3. 停止长时任务。 - - ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - import featureAbility from '@ohos.ability.featureAbility'; - - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - - ``` - -基于Stage模型: - -1. 新建Api Version 9的工程后,在工程目录中右键选择“New” -> “Ability” 快速创建Ability组件。并在module.json5文件中配置长时任务权限、后台模式类型。 - - ``` - "module": { - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // 后台模式类型 - } - ], - "requestPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 - } - ] - } - ``` - -2. 申请长时任务。 - - ```ts - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - import wantAgent from '@ohos.wantAgent'; - - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); - ``` - -3. 停止长时任务。 - - ```ts - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - - ``` - - -### 开发实例 - -基于FA模型: - -基于FA的Service Ability使用,参考[ServiceAbility开发指导](../ability/fa-serviceability.md)。 - -当不需要与后台执行的长时任务交互时,可以采用startAbility()方法启动Service Ability。并在Service Ability的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。当任务执行完,再调用长时任务取消接口,及时释放资源。 - -当需要与后台执行的长时任务交互时(如播放音乐等)。可以采用connectAbility()方法启动并连接Service Ability。在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.wantAgent'; -import rpc from "@ohos.rpc"; - -function startContinuousTask() { - let wantAgentInfo = { - // 点击通知后,将要执行的动作列表 - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - // 点击通知后,动作类型 - operationType: wantAgent.OperationType.START_ABILITY, - // 使用者自定义的一个私有值 - requestCode: 0, - // 点击通知后,动作执行属性 - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); -} - -function stopContinuousTask() { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); -} - -async function processAsyncJobs() { - // 此处执行具体的长时任务。 - - // 长时任务执行完,调用取消接口,释放资源。 - stopContinuousTask(); -} - -let mMyStub; - -class MyStub extends rpc.RemoteObject { - constructor(des) { - if (typeof des === 'string') { - super(des); - } else { - return null; - } - } - onRemoteRequest(code, data, reply, option) { - console.log('ServiceAbility onRemoteRequest called'); - // code 的具体含义用户自定义 - if (code === 1) { - // 接收到申请长时任务的请求码 - startContinuousTask(); - // 此处执行具体长时任务 - } else if (code === 2) { - // 接收到取消长时任务的请求码 - stopContinuousTask(); - } else { - console.log('ServiceAbility unknown request code'); - } - return true; - } -} - -export default { - onStart(want) { - console.info('ServiceAbility onStart'); - mMyStub = new MyStub("ServiceAbility-test"); - // 在执行后台长时任前,调用申请接口。 - startContinuousTask(); - processAsyncJobs(); - }, - onStop() { - console.info('ServiceAbility onStop'); - }, - onConnect(want) { - console.info('ServiceAbility onConnect'); - return mMyStub; - }, - onReconnect(want) { - console.info('ServiceAbility onReconnect'); - }, - onDisconnect() { - console.info('ServiceAbility onDisconnect'); - }, - onCommand(want, restart, startId) { - console.info('ServiceAbility onCommand'); - } -}; -``` - -基于Stage模型: - -Stage模型的相关信息参考[Stage模型综述](../ability/stage-brief.md)。 -当应用需要在后台执行长时任务时,可以通过Call的方式在后台创建并运行Ability。使用方式参考[Call调用开发指导](../ability/stage-call.md)。 - -```ts -import Ability from '@ohos.application.Ability' -import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; - -let mContext = null; - -function startContinuousTask() { - let wantAgentInfo = { - // 点击通知后,将要执行的动作列表 - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - // 点击通知后,动作类型 - operationType: wantAgent.OperationType.START_ABILITY, - // 使用者自定义的一个私有值 - requestCode: 0, - // 点击通知后,动作执行属性 - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(mContext, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); -} - -function stopContinuousTask() { - backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); -} - -class MySequenceable { - num: number = 0; - str: String = ""; - - constructor(num, string) { - this.num = num; - this.str = string; - } - - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - return true; - } - - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - return true; - } -} - -function sendMsgCallback(data) { - console.info('BgTaskAbility funcCallBack is called ' + data) - let receivedData = new Mysequenceable(0, "") - data.readSequenceable(receivedData) - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) - if (receivedData.str === 'start_bgtask') { - startContinuousTask() - } else if (receivedData.str === 'stop_bgtask') { - stopContinuousTask(); - } - return new Mysequenceable(10, "Callee test"); -} - -export default class BgTaskAbility extends Ability { - onCreate(want, launchParam) { - console.info("[Demo] BgTaskAbility onCreate") - this.callee.on("test", sendMsgCallback); - - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback) - } catch (error) { - console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) - } - mContext = this.context; - } - - onDestroy() { - console.info("[Demo] BgTaskAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - console.info("[Demo] BgTaskAbility onWindowStageCreate") - - windowStage.loadContent("pages/second").then((data)=> { - console.info(`load content succeed with data ${JSON.stringify(data)}`) - }).catch((error)=>{ - console.error(`load content failed with error ${JSON.stringify(error)}`) - }) - } - - onWindowStageDestroy() { - console.info("[Demo] BgTaskAbility onWindowStageDestroy") - } - - onForeground() { - console.info("[Demo] BgTaskAbility onForeground") - } - - onBackground() { - console.info("[Demo] BgTaskAbility onBackground") - } -}; -``` - -## 能效资源申请 - -### 接口说明 - -**表1** 能效资源申请主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------------------- | -| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | 申请能效资源。 | -| resetAllEfficiencyResources():void | 释放申请的能效资源。 | - - -### 开发步骤 - - -1. 申请能效资源 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -let request = { - resourceTypes: backgroundTaskManager.ResourceType.CPU, - isApply: true, - timeOut: 0, - reason: "apply", - isPersist: true, - isProcess: true, -}; -let res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); -``` - -2. 释放申请的部分资源 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -let request = { - resourceTypes: backgroundTaskManager.ResourceType.CPU, - isApply: false, - timeOut: 0, - reason: "reset", -}; -let res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); -``` - -3. 释放申请的所有资源 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); -``` - -### 开发实例 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -// 申请能效资源 -let request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | - backgroundTaskManager.ResourceType.TIMER, - isApply: true, - timeOut: 0, - reason: "apply", - isPersist: true, - isProcess: true, -}; -let res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); - -// 释放部分资源 -request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, - isApply: false, - timeOut: 0, - reason: "reset", -}; -res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); - -// 释放全部资源 -backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); -``` - -## 相关实例 - -基于后台任务管理,有以下相关实例可供参考: - -- [`BackgroundTaskManager`:后台任务管理(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/background-task-overview.md b/zh-cn/application-dev/task-management/background-task-overview.md index a045739051f012c791ca6b093c0afc362ebd7749..c24d818516a8d473bca665304c4d8851f2b531f2 100644 --- a/zh-cn/application-dev/task-management/background-task-overview.md +++ b/zh-cn/application-dev/task-management/background-task-overview.md @@ -1,26 +1,32 @@ # 后台任务概述 -后台应用频繁活动,会造成用户设备耗电快、卡顿等现象。因此,为了支撑性能、功耗诉求,系统仅允许应用在后台执行规范内的活动,规范外的活动默认会被挂起,当资源不足时会被回收。同时,应用可以申请能效资源,保证自己在一段时间内不会被挂起,或者在挂起状态能够正常使用一些资源,例如公共事件、计时器等。 +后台应用频繁活动,会造成用户设备耗电快、卡顿等现象。因此,为了支撑性能、功耗诉求,系统仅允许应用在后台执行规范内的活动,规范外的活动默认会被挂起,当资源不足时会被回收。 +针对应用或业务模块处于后台(无可见界面)时,有需要继续执行或者后续执行的业务,可基于业务类型,申请[短时任务](#短时任务)延迟挂起或者[长时任务](#长时任务)避免进入挂起状态;使用[延迟调度任务](#延迟任务),执行对实时性要求不高的任务;同时针对特权应用,如果需要更加灵活的配置,可以申请[能效资源](#申请能效资源)。 ## 后台任务类型 -本文描述的后台任务特指应用或业务模块处于后台(无可见界面)时,有需要继续执行或者后续执行的业务。OpenHarmony将后台任务分为三种类型,并执行不同的处理: +OpenHarmony将后台任务分为四种类型,并提供了一个资源申请的扩展功能: - **1. 无后台业务** :应用或业务模块退到后台后,无任务需要处理。 + **无后台业务** :应用或业务模块退到后台后,无任务需要处理。 - **2. 短时任务** :应用或业务模块退到后台后,如果有紧急不可推迟且短时间能完成的任务,如应用退后台要进行数据压缩,不可中断,则使用短时任务申请延迟进入挂起(Suspend)状态。 + **短时任务** :应用或业务模块退到后台后,如果有紧急不可推迟且短时间能完成的任务,如应用退后台要进行数据压缩,不可中断,则使用短时任务申请延迟进入挂起(Suspend)状态。 - **3. 长时任务** :如果是用户发起的可感知业务需要长时间后台运行,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 + **长时任务** :如果是用户发起的可感知业务需要长时间后台运行,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 - **4. 能效资源** :能效资源包括CPU资源、WORK_SCHEDULER资源、软件资源(COMMON_EVENT, TIMER)、硬件资源(GPS, BLUETOOTH)。如果应用或者进程申请了能效资源,那么根据能效资源的类型会拥有相应的特权,例如申请了CPU资源的可以不被挂起,申请了WORK_SCHEDULER后延时任务可以拥有更长的执行时间。 + **延迟任务** :延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性不高的任务。当满足设定条件的时候,任务会被放入待调度队列,当系统空闲时调度该任务。 + **能效资源** :能效资源包括CPU资源、WORK_SCHEDULER资源、软件资源(COMMON_EVENT, TIMER)、硬件资源(GPS, BLUETOOTH)。如果应用或者进程申请了能效资源,那么根据能效资源的类型会拥有相应的特权,例如申请了CPU资源的可以不被挂起,申请了WORK_SCHEDULER后延时任务可以拥有更长的执行时间。 + +## 最佳后台任务选择 + +![后台任务选择](public_sys-resources/bgtask_choice.png) ## 短时任务 退到后台的应用有不可中断且短时间能完成的任务时,可以使用短时任务机制。该机制允许应用在后台短时间内完成任务,保障应用业务运行不受后台生命周期管理的影响。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** > 短时任务仅针对应用的临时任务提供资源使用生命周期保障,限制单次最大使用时长为3分钟,全天使用配额默认为10分钟(具体时长系统根据应用场景和系统状态智能调整)。 @@ -63,9 +69,44 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业 - 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。 - 一个Ability同一时刻只能申请运行一个长时任务。 -## 能效资源申请 -能效资源可以分为四种,CPU资源,WORK_SCHEDULER资源,软件资源(COMMON_EVENT,TIMER),硬件资源(GPS,BLOOTOOTH,AUDIO)。 -应用或进程申请能效资源后能够获得相应特权,例如:申请CPU资源后可以不被挂起;申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加;申请软件、硬件资源后,相关资源在挂起状态下不被代理。 +## 延迟任务 +延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性要求不高的任务,比如设备空闲时候做一次数据学习等场景。当应用申请延迟任务的时候,任务会被放入待调度队列,系统会根据当前状态,如内存、功耗、温度等统一决策最优的调度时机。同时支持任务的持久化,应用退出或者设备重启,设置的任务同样能够被触发。 + +### 延迟任务调度约束 + +延迟调度任务的使用需要遵从如下约束和规则: + +- **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。默认的超时限制为2分钟,对于系统应用,可以通过[申请能效资源](efficiency-resources-apply-dev-guide.md)获取更长的执行时间(充电状态20分钟,非充电状态10分钟)。 +- **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。对于通过能效资源接口申请了WORK_SCHEDULER资源的应用,在资源的有效期内,它的延迟任务执行频率不受限制。 + + | 应用分组 | 延迟任务执行频率约束 | + | --------------------|------------------------- | + | 活跃 | 最小间隔2小时 | + | 每日使用 | 最小间隔4小时 | + | 经常使用 | 最小间隔24小时 | + | 不经常使用 | 最小间隔48小时 | + | 受限分组 | 禁止 | + | 未使用分组 | 禁止 | + | [能效资源豁免分组](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | 执行频率不受限制 | + +- **WorkInfo设置参数约束** + + - workId、bundleName、abilityName为必填项,bundleName必须填本应用,否则校验失败。 + + - 至少要设置一个满足的条件。 + + - 重复任务时间间隔至少20分钟,当设置重复任务时间间隔时,必须设置始终重复和重复次数中的一个。 + + - 携带参数信息支持number、string、bool三种类型。 + +## 申请能效资源 +能效资源可以分为四种:CPU资源,WORK_SCHEDULER资源,软件资源(COMMON_EVENT,TIMER),硬件资源(GPS,BLUETOOTH,AUDIO)。 + +应用或进程申请能效资源后能够获得相应特权: + * 申请CPU资源后可以不被挂起,直到任务完成。 + * 申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加 + * 申请COMMON_EVENT资源后,应用在后台处于挂起状态时,仍然能够接收到系统公共事件,申请TIMER资源后,应用能够使用定时器执行精确定时任务、 + * 申请硬件资源后,应用在后台被挂起后,依然能够被相关服务唤醒,执行相应的任务。 **表1** 能效资源种类 @@ -84,3 +125,4 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业 - 能效资源申请或者释放可以由进程或者应用发起,由应用发起的资源释放会释放属于它的同类型的所有资源,包括进程申请的资源。例如应用申请了CPU资源,进程申请了CPU和WORK_SCHEDULER资源,当应用释放CPU资源的时候,会将进程的CPU资源一同释放,同时不同类型的WORK_SCHEDULER资源不受影响。由进程发起的资源释放对应用申请的资源没有影响,例如当应用和进程同时申请了CPU,进程发起了CPU资源释放,应用的CPU资源不会被释放。 - 同时申请同一类持久资源和非持久资源,持久资源会覆盖非持久资源,在超时时不会释放资源。例如应用首先申请了10s的CPU资源,然后在第5s的时候申请了持久的CPU资源,那么资源会变成持久的,非持久的CPU资源记录会被持久化的CPU资源记录覆盖,到了第10s的时候资源不会被释放,如果在第8s的时候提前释放了资源,那么会将CPU资源释放,无法单独释放其中非持久的或者持久的CPU资源。 - WORK_SCHEDULER资源只能由应用申请和释放,不能由进程申请和释放。 +- 需要使用能效资源的应用,需要向应用中心提出申请,获取相应的特权。 diff --git a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..9d50c74836d61261433ced3a5a6b30e10163f446 --- /dev/null +++ b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md @@ -0,0 +1,429 @@ +# 长时任务 + +## 场景说明 + +如果应用需要在后台长时间执行用户可感知的任务,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 +长时任务在后台执行没有时间限制。为了避免该机制被滥用,系统只允许申请有限个数的长时任务类型,同时会有相应的通知提示与长时任务相关联,使用户可感知,并且系统会添加相应的校验机制,确保应用是的确在执行相应的长时任务。 + +## 接口说明 + +**表1** 长时任务主要接口 + +| 接口名 | 描述 | +| ---------------------------------------- | ---------------------------- | +| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> | 服务启动后,向系统申请长时任务,使服务一直保持后台运行。 | +| stopBackgroundRunning(context: Context): Promise<void> | 停止后台长时任务的运行。 | + + +其中,wantAgent的信息详见([WantAgent](../reference/apis/js-apis-wantAgent.md)) + +**表2** 后台模式类型 + +| 参数名 | id值 | 描述 | 配置项 | +| ----------------------- | ---- | -------------- | --------------------- | +| DATA_TRANSFER | 1 | 数据传输 | dataTransfer | +| AUDIO_PLAYBACK | 2 | 音频播放 | audioPlayback | +| AUDIO_RECORDING | 3 | 录音 | audioRecording | +| LOCATION | 4 | 定位导航 | location | +| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | bluetoothInteraction | +| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | multiDeviceConnection | +| WIFI_INTERACTION | 7 | WLAN相关(系统保留) | wifiInteraction | +| VOIP | 8 | 音视频通话(系统保留) | voip | +| TASK_KEEPING | 9 | 计算任务(仅供特定设备使用) | taskKeeping | + + +## 开发步骤 + +### 基于FA模型 + +基于FA的Service Ability使用,参考[ServiceAbility开发指导](../ability/fa-serviceability.md)。 + +当不需要与后台执行的长时任务交互时,可以采用startAbility()方法启动Service Ability。并在Service Ability的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。当任务执行完,再调用长时任务取消接口,及时释放资源。 + +当需要与后台执行的长时任务交互时(如播放音乐等)。可以采用connectAbility()方法启动并连接Service Ability。在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 + +1、新建Api Version 8的工程后,在工程目录中右键选择“new” -> “Ability” -> “Service Ability” 快速创建Service Ability组件。并在config.json文件中配置长时任务权限ohos.permission.KEEP_BACKGROUND_RUNNING、后台模式类型,其中Ability类型为“service”。 + +``` +"module": { + "package": "com.example.myapplication", + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // 后台模式类型 + "type": "service" // ability类型为service + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 + } + ] +} +``` + +2、在Service Ability调用长时任务的申请和取消接口。 + +```js +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.wantAgent'; +import rpc from "@ohos.rpc"; + +function startContinuousTask() { + let wantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); +} + +function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } +} + +async function processAsyncJobs() { + // 此处执行具体的长时任务。 + + // 长时任务执行完,调用取消接口,释放资源。 + stopContinuousTask(); +} + +let mMyStub; + +class MyStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + onRemoteRequest(code, data, reply, option) { + console.log('ServiceAbility onRemoteRequest called'); + // code 的具体含义用户自定义 + if (code === 1) { + // 接收到申请长时任务的请求码 + startContinuousTask(); + // 此处执行具体长时任务 + } else if (code === 2) { + // 接收到取消长时任务的请求码 + stopContinuousTask(); + } else { + console.log('ServiceAbility unknown request code'); + } + return true; + } +} + +export default { + onStart(want) { + console.info('ServiceAbility onStart'); + mMyStub = new MyStub("ServiceAbility-test"); + // 在执行后台长时任前,调用申请接口。 + startContinuousTask(); + processAsyncJobs(); + }, + onStop() { + console.info('ServiceAbility onStop'); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return mMyStub; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, restart, startId) { + console.info('ServiceAbility onCommand'); + } +}; +``` + +### 基于Stage模型 + +Stage模型的相关信息参考[Stage模型综述](../ability/stage-brief.md)。 + +1、新建Api Version 9的工程后,在工程目录中右键选择“New” -> “Ability” 快速创建Ability组件。并在module.json5文件中配置长时任务权限ohos.permission.KEEP_BACKGROUND_RUNNING、后台模式类型。 + +``` +"module": { + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // 后台模式类型 + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 + } + ] +} +``` + +2、在应用内执行长时任务时,由于元能力启动管控规则限制,不支持同应用通过startAbilityByCall的形式在后台创建并运行Ability。可以直接在page中,执行相应的代码。Stage模型的Ability使用参考[Ability开发指导](../ability/stage-ability.md)。 + +```ts +import wantAgent from '@ohos.wantAgent'; +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + +@Entry +@Component +struct Index { + @State message: string = 'test' + // 通过getContext方法,来获取page所在的Ability上下文。 + private context: any = getContext(this) + + startContinuousTask() { + let wantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } + + stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + } + + build() { + Row() { + Column() { + Text("Index") + .fontSize(50) + .fontWeight(FontWeight.Bold) + + Button() { Text('申请长时任务').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // 通过按钮申请长时任务 + this.startContinuousTask(); + + // 此处执行具体的长时任务逻辑,如放音等。 + }) + + Button() { Text('取消长时任务').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // 此处结束具体的长时任务的执行 + + // 通过按钮取消长时任务 + this.stopContinuousTask(); + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +3、当需要跨设备或者跨应用在后台执行长时任务时,可以通过Call的方式在后台创建并运行Ability。使用方式参考[Call调用开发指导](../ability/stage-call.md)。 + +```ts +import Ability from '@ohos.application.Ability' +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import wantAgent from '@ohos.wantAgent'; + +const MSG_SEND_METHOD: string = 'CallSendMsg' + +let mContext = null; + +function startContinuousTask() { + let wantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((error) => { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); +} + +function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } +} + +class MySequenceable { + num: number = 0; + str: String = ""; + + constructor(num, string) { + this.num = num; + this.str = string; + } + + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } +} + +function sendMsgCallback(data) { + console.info('BgTaskAbility funcCallBack is called ' + data) + let receivedData = new MySequenceable(0, "") + data.readSequenceable(receivedData) + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) + // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 + if (receivedData.str === 'start_bgtask') { + startContinuousTask() + } else if (receivedData.str === 'stop_bgtask') { + stopContinuousTask(); + } + return new MySequenceable(10, "Callee test"); +} + +export default class BgTaskAbility extends Ability { + onCreate(want, launchParam) { + console.info("[Demo] BgTaskAbility onCreate") + this.callee.on("test", sendMsgCallback); + + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + mContext = this.context; + } + + onDestroy() { + console.info("[Demo] BgTaskAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + console.info("[Demo] BgTaskAbility onWindowStageCreate") + + windowStage.loadContent("pages/index").then((data)=> { + console.info(`load content succeed with data ${JSON.stringify(data)}`) + }).catch((error)=>{ + console.error(`load content failed with error ${JSON.stringify(error)}`) + }) + } + + onWindowStageDestroy() { + console.info("[Demo] BgTaskAbility onWindowStageDestroy") + } + + onForeground() { + console.info("[Demo] BgTaskAbility onForeground") + } + + onBackground() { + console.info("[Demo] BgTaskAbility onBackground") + } +}; +``` + +## 相关实例 + +基于后台任务管理,有以下相关实例可供参考: + +- [`BackgroundTaskManager`:后台任务管理(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md b/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..ebdd94a0c1a20876b854d16a19725ad854c773f2 --- /dev/null +++ b/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md @@ -0,0 +1,53 @@ +## 申请能效资源 + +### 场景说明 + +在实际的系统中,存在一些重要性高的系统应用,虽然此类应用相比普通应用具有一定的特权,但为了进一步平衡系统的功耗开销,这些应用同样需要支持在后台可被挂起。但对于系统特权应用,为了避免挂起后重要功能受到影响,提供了独立的能效资源申请接口,使这些特权应用可以在后台执行一些特殊的任务和使用特定的系统资源,例如在被挂起期间如果仍然希望能够收到系统公共事件,可以使用能效资源接口向系统申请使用公共事件资源。 + +对于需要升级为特权应用的,开发者需要合理评估自己的业务诉求,向应用中心提出申请。 + +### 接口说明 + +**表1** 申请能效资源主要接口 + +| 接口名 | 描述 | +| ---------------------------------------- | ---------------------------------------- | +| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | 申请能效资源。 | +| resetAllEfficiencyResources():void | 释放申请的能效资源。 | + + +### 开发步骤 + +1、当特权应用需要在后台使用特殊资源时。向系统申请目标资源。 + +2、当资源使用完毕,需要及时释放。支持释放部分资源或全部资源。 + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +// 申请能效资源 +let request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | + backgroundTaskManager.ResourceType.TIMER, + isApply: true, + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: true, +}; +let res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); + +// 释放部分资源 +request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, + isApply: false, + timeOut: 0, + reason: "reset", +}; +res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); + +// 释放全部资源 +backgroundTaskManager.resetAllEfficiencyResources(); +``` diff --git a/zh-cn/application-dev/task-management/public_sys-resources/bgtask_choice.png b/zh-cn/application-dev/task-management/public_sys-resources/bgtask_choice.png new file mode 100644 index 0000000000000000000000000000000000000000..4f1fd6eefab0302ba4f936828adefbedf8f6c1f8 Binary files /dev/null and b/zh-cn/application-dev/task-management/public_sys-resources/bgtask_choice.png differ diff --git a/zh-cn/application-dev/task-management/transient-task-dev-guide.md b/zh-cn/application-dev/task-management/transient-task-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..86ca50c4f7c8c8a3d0d606280ac2dd520e941531 --- /dev/null +++ b/zh-cn/application-dev/task-management/transient-task-dev-guide.md @@ -0,0 +1,84 @@ +# 短时任务 + +## 场景说明 + +当应用退到后台默认有6到12秒的运行时长,超过该时间后,系统会将应用置为挂起状态。对于绝大多数应用,6到12秒的时间,足够执行一些重要的任务,但如果应用需要更多的时间,可以通过短时任务接口,扩展应用的执行时间。 +建议不要等到应用退后台后,才调用requestSuspendDelay方法申请延迟挂起,而是应该在执行任何的耗时操作前,都应该调用该接口,向系统申明扩展应用的执行时间。 +当应用在前台时,使用requestSuspendDelay方法,不会影响应用的短时任务配额。 + +由于每个应用每天的短时任务配额时间有限,当执行完耗时任务后,应当及时取消延迟挂起的申请。 + +一些典型的耗时任务有,需要保存一些状态数据到本地数据库,需要打开和处理一个大型文件,需要同步一些数据到应用的云端服务器等。 + + +## 接口说明 + + +**表1** 短时任务主要接口 + +| 接口名 | 描述 | +| ---------------------------------------- | ---------------------------------------- | +| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | 后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为180000,低电量时默认值为60000。 | +| getRemainingDelayTime(requestId: number): Promise<number> | 获取应用程序进入挂起状态前的剩余时间。
使用Promise形式返回。 | +| cancelSuspendDelay(requestId: number): void | 取消延迟挂起。 | + + +## 开发步骤 + +1、当应用需要开始执行一个耗时的任务时。调用短时任务申请接口,并且在任务执行完后,调用短时任务取消接口。 + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +let delayInfo; +let id; + +// 申请延迟挂起 +function requestSuspendDelay() { + let myReason = 'test requestSuspendDelay'; + delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); + // 此回调函数执行,表示应用的延迟挂起申请即将超时,应用需要执行一些清理和标注工作。 + }); + + id = delayInfo.requestId; + console.info("requestId is: " + id); +} + +// 获取进入挂起前的剩余时间 +function getRemainingDelayTime() { + let delayTime = 0; + backgroundTaskManager.getRemainingDelayTime(id).then((res) => { + console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); + delayTime = res; + }).catch((err) => { + console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); + }); + return delayTime; +} + +// 取消延迟挂起 +function cancelSuspendDelay() { + backgroundTaskManager.cancelSuspendDelay(id); +} + +function performingLongRunningTask() { + // 在执行具体的耗时任务前,调用短时任务申请接口。向系统申请延迟挂起,延长应用的后台执行时间。 + requestSuspendDelay(); + + // 通过剩余时间查询接口,获取可用时间配额。 + let delayTime = getRemainingDelayTime(); + + if (delayTime < 0) { // 如果时间配置少于一定的大小,考虑取消此次耗时操作。 + // 处理短时任务配额时间不够的场景 + + cancelSuspendDelay(); + return; + } + + // 此处执行具体的耗时任务。 + + // 耗时任务执行完,调用短时任务取消接口,避免配额浪费。 + cancelSuspendDelay(); +} +``` diff --git a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md index 625b3046cc8f3c16e03de8ecc96dab436b722c38..9b837f39fd9aa3e699fcf74f06cf8565078e8397 100644 --- a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md +++ b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md @@ -2,51 +2,39 @@ ## 场景介绍 -应用要执行对实时性要求不高的任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间。延迟任务调度约束见[延迟任务调度概述](./work-scheduler-overview.md)。 - +应用要执行对实时性要求不高的任务或持久性任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间。延迟任务调度约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束)。 ## 接口说明 -注册相关接口包导入: -```js -import workScheduler from '@ohos.workScheduler'; -``` - -回调相关接口包导入: -```js -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; -``` - -### 延迟任务调度 **表1** workScheduler主要接口 接口名 | 接口描述 ---------------------------------------------------------|----------------------------------------- -startWork(work: WorkInfo): boolean; | 延迟调度任务申请 -stopWork(work: WorkInfo, needCancel?: boolean): boolean; | 延迟调度任务取消 +startWork(work: WorkInfo): void; | 延迟调度任务申请 +stopWork(work: WorkInfo, needCancel?: boolean): void; | 延迟调度任务取消 getWorkStatus(workId: number, callback: AsyncCallback\): void;| 获取延迟调度任务状态(Callback形式) getWorkStatus(workId: number): Promise\; | 获取延迟调度任务状态(Promise形式) obtainAllWorks(callback: AsyncCallback\): Array\;| 获取所有延迟调度任务(Callback形式) obtainAllWorks(): Promise>;| 获取所有延迟调度任务(Promise形式) -stopAndClearWorks(): boolean;| 停止并清除任务 +stopAndClearWorks(): void;| 停止并清除任务 isLastWorkTimeOut(workId: number, callback: AsyncCallback\): boolean;| 获取上次任务是否超时(针对RepeatWork,Callback形式) isLastWorkTimeOut(workId: number): Promise\;| 获取上次任务是否超时(针对RepeatWork,Promise形式) **表2** WorkInfo包含参数 -> **说明:** WorkInfo设置参数约束见[延迟任务调度概述](./work-scheduler-overview.md) +WorkInfo设置参数约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束) 参数名| 类型 |描述 ---------------------------------------------------------|-----------------------------------------|--------------------------------------------------------- workId| number | 延迟任务Id(必填) bundleName| string | 延迟任务包名(必填) abilityName| string | 延迟任务回调通知的组件名(必填) -networkType | [NetworkType](../reference/apis/js-apis-workScheduler.md#networktype) | 网络类型 +networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | 网络类型 isCharging| boolean | 是否充电 -chargerType| [ChargingType](../reference/apis/js-apis-workScheduler.md#chargingtype) | 充电类型 +chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | 充电类型 batteryLevel| number | 电量 -batteryStatus| [BatteryStatus](../reference/apis/js-apis-workScheduler.md#batterystatus) | 电池状态 -storageRequest| [StorageRequest](../reference/apis/js-apis-workScheduler.md#storagerequest) |存储状态 +batteryStatus| [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | 电池状态 +storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) |存储状态 isRepeat| boolean |是否循环任务 repeatCycleTime| number |循环间隔 repeatCount | number|循环次数 @@ -61,138 +49,151 @@ onWorkStop(work: WorkInfo): void | 延迟调度任务结束回调 ### 开发步骤 -**开发对应的Extension** +1、导入模块。 - import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; - - export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); - } - onWorkStop(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); - } - } +注册相关接口包导入: +```js +import workScheduler from '@ohos.resourceschedule.workScheduler'; +``` +回调相关接口包导入: +```js +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; +``` -**注册延迟任务** +2、开发对应的ExtensionAbility,用于回调执行具体的延迟任务。关于ExtensionAbility的介绍,参考[ExtensionAbility机制](../ability/stage-brief.md#extensionability机制)。 - import workScheduler from '@ohos.workScheduler'; - - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } - } - var res = workScheduler.startWork(workInfo); - console.info("workschedulerLog res:" + res); +```ts +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; +export default class MyExtension extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); + } + onWorkStop(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); + } +} +``` -**取消延迟任务** +3、注册延迟任务 - import workScheduler from '@ohos.workScheduler'; +```ts +import workScheduler from '@ohos.resourceschedule.workScheduler'; - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } - } - var res = workScheduler.stopWork(workInfo, false); - console.info("workschedulerLog res:" + res); - - -**获取指定延迟任务** +let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } +} +try{ + workScheduler.startWork(workInfo); + console.info('workschedulerLog startWork success'); +} catch (error) { + console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`); +} +``` -1.Callback写法 - workScheduler.getWorkStatus(50, (err, res) => { - if (err) { - console.info('workschedulerLog getWorkStatus failed, because:' + err.code); - } else { - for (let item in res) { - console.info('workschedulerLog getWorkStatuscallback success,' + item + ' is:' + res[item]); - } - } - }); +4、取消延迟任务 + +```ts +import workScheduler from '@ohos.resourceschedule.workScheduler'; + +let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } +} +try{ + workScheduler.stopWork(workInfo, false); + console.info('workschedulerLog stopWork success'); +} catch (error) { + console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`); +} +``` -2.Promise写法 +5、获取指定延迟任务 - workScheduler.getWorkStatus(50).then((res) => { +```ts +try{ + workScheduler.getWorkStatus(50, (error, res) => { + if (error) { + console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); + } else { for (let item in res) { - console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]); + console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); } - }).catch((err) => { - console.info('workschedulerLog getWorkStatus failed, because:' + err.code); - }) - - -**获取所有延迟任务** - -1.Callback写法 - - workScheduler.obtainAllWorks((err, res) =>{ - if (err) { - console.info('workschedulerLog obtainAllWorks failed, because:' + err.code); - } else { - console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res)); - } - }); + } + }); +} catch (error) { + console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`); +} +``` -2.Promise写法 - workScheduler.obtainAllWorks().then((res) => { - console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res)); - }).catch((err) => { - console.info('workschedulerLog obtainAllWorks failed, because:' + err.code); - }) +6、获取所有延迟任务 -**停止并清除任务** +```ts +try{ + workScheduler.obtainAllWorks((error, res) =>{ + if (error) { + console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); + } + }); +} catch (error) { + console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`); +} +``` - let res = workScheduler.stopAndClearWorks(); - console.info("workschedulerLog res:" + res); +7、停止并清除任务 -**判断上次执行是否超时** +```ts +try{ + workScheduler.stopAndClearWorks(); + console.info(`workschedulerLog stopAndClearWorks success`); +} catch (error) { + console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`); +} +``` -1.Callback写法 +8、判断上次执行是否超时 - workScheduler.isLastWorkTimeOut(500, (err, res) =>{ - if (err) { - console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code); - } else { - console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res); - } - }); - -2.Promise写法 - - workScheduler.isLastWorkTimeOut(500) - .then(res => { - console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res); - }) - .catch(err => { - console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code); - }); - }) +```ts +try{ + workScheduler.isLastWorkTimeOut(500, (error, res) =>{ + if (error) { + onsole.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); + } else { + console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); + } + }); +} catch (error) { + console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`); +} +``` ## 相关实例 diff --git a/zh-cn/application-dev/task-management/work-scheduler-overview.md b/zh-cn/application-dev/task-management/work-scheduler-overview.md deleted file mode 100644 index da6a08d7881862a29ac15069cabfe5c47cbe77d9..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/work-scheduler-overview.md +++ /dev/null @@ -1,34 +0,0 @@ -# 延迟任务调度概述 - -延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性不高的任务。当满足设定条件的时候,任务会被放入待调度队列,当系统空闲时调度该任务。 - -## 使用说明 - -应用要执行对实时性要求不高的任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时机。 - -## 延迟任务调度约束 - -延迟调度任务的使用需要遵从如下约束和规则: - -- **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。默认的超时限制为2分钟,对于系统应用,可以通过[能效资源申请接口](background-task-overview.md#能效资源申请)获取更长的执行时间(充电状态20分钟,非充电状态10分钟)。 -- **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。对于通过能效资源接口申请了WORK_SCHEDULER资源的应用,在资源的有效期内,它的延迟任务执行频率不受限制。 - -应用分组 | 延迟任务执行频率约束 ---------------------|------------------------- -活跃 | 最小间隔2小时 -每日使用 | 最小间隔4小时 -经常使用 | 最小间隔24小时 -不经常使用 | 最小间隔48小时 -受限分组 | 禁止 -未使用分组 | 禁止 -[能效资源豁免分组](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | 执行频率不受限制 - -- **WorkInfo设置参数约束** - -(1) workId、bundleName、abilityName为必填项,bundleName必须填本应用,否则校验失败。 - -(2)至少要设置一个满足的条件。 - -(3)重复任务时间间隔至少20分钟,当设置重复任务时间间隔时,必须设置始终重复和重复次数中的一个。 - -(4)携带参数信息支持number、string、bool三种类型。 \ No newline at end of file diff --git a/zh-cn/application-dev/ui/Readme-CN.md b/zh-cn/application-dev/ui/Readme-CN.md index 8131710e12f0374526d018ad93b998b7aff41f45..d03fff8c0fba8cd04f1d54a8eee65791d58f830b 100755 --- a/zh-cn/application-dev/ui/Readme-CN.md +++ b/zh-cn/application-dev/ui/Readme-CN.md @@ -3,37 +3,31 @@ - [方舟开发框架(ArkUI)概述](arkui-overview.md) - UI开发(基于ArkTS的声明式开发范式) - [概述](ui-ts-overview.md) - - 框架说明 - - 文件组织 - - [目录结构](ts-framework-directory.md) - - [应用代码文件访问规则](ts-framework-file-access-rules.md) - - 资源管理 - - [资源文件的分类](ui-ts-basic-resource-file-categories.md) - - [资源访问](ts-resource-access.md) - - [像素单位](ts-pixel-units.md) - - - 深入理解组件化 - - [自定义组件初始化](ts-custom-component-initialization.md) - - [自定义组件生命周期回调函数](ts-custom-component-lifecycle-callbacks.md) - - [组件创建和重新初始化示例](ts-component-creation-re-initialization.md) - - 常见组件开发指导 - - [Button开发指导](ui-ts-basic-components-button.md) - - [Web开发指导](ui-ts-components-web.md) - - 常见布局开发指导 - - [弹性布局](ui-ts-layout-flex.md) - - [栅格布局](ui-ts-layout-grid-container.md) - - [媒体查询](ui-ts-layout-mediaquery.md) - - 体验声明式UI - - [创建声明式UI工程](ui-ts-creating-project.md) - - [初识Component](ui-ts-components.md) - - [创建简单视图](ui-ts-creating-simple-page.md) - - 页面布局与连接 + - [声明式UI开发指导](ui-ts-developing-intro.md) + - 声明式UI开发实例 + - [创建简单视图](ui-ts-creating-simple-page.md) + - 构建完整实例 - [构建食物数据模型](ui-ts-building-data-model.md) - [构建食物列表List布局](ui-ts-building-category-list-layout.md) - [构建食物分类Grid布局](ui-ts-building-category-grid-layout.md) - - [页面跳转与数据传递](ui-ts-page-redirection-data-transmission.md) - - [性能提升的推荐方法](ts-performance-improvement-recommendation.md) - + - [页面跳转与数据传递](ui-ts-page-redirection-data-transmission.md) + - 添加闪屏动画 + - [绘制图像](ui-ts-drawing-feature.md) + - [添加动画效果](ui-ts-animation-feature.md) + - [常用组件说明](ui-ts-components-intro.md) + - 常见布局开发指导 + - 自适应布局 + - [线性布局](ui-ts-layout-linear.md) + - [层叠布局](ui-ts-layout-stack.md) + - [弹性布局](ui-ts-layout-flex.md) + - [网格布局](ui-ts-layout-grid.md) + - 响应式布局 + - [栅格布局(新)](ui-ts-layout-grid-container-new.md) + - [栅格布局](ui-ts-layout-grid-container.md) + - [媒体查询](ui-ts-layout-mediaquery.md) + - [自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md) + - [Web组件开发指导](ui-ts-components-web.md) + - [性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md) - UI开发(兼容JS的类Web开发范式) - [概述](ui-js-overview.md) - 框架说明 diff --git a/zh-cn/application-dev/ui/figures/LazyForEach1.gif b/zh-cn/application-dev/ui/figures/LazyForEach1.gif new file mode 100644 index 0000000000000000000000000000000000000000..66730a7cdb85529ed96a084b9d9b98aaed18474d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/LazyForEach1.gif differ diff --git a/zh-cn/application-dev/ui/figures/aboutToAppear.gif b/zh-cn/application-dev/ui/figures/aboutToAppear.gif new file mode 100644 index 0000000000000000000000000000000000000000..6bddc173b59f69a746592ae8689b0443b704a8b3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/aboutToAppear.gif differ diff --git a/zh-cn/application-dev/ui/figures/alignself.png b/zh-cn/application-dev/ui/figures/alignself.png new file mode 100644 index 0000000000000000000000000000000000000000..6ab6ba66e53bf7dc3edd72d44727fe40c7ff0fb9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/alignself.png differ diff --git a/zh-cn/application-dev/ui/figures/animation-feature.gif b/zh-cn/application-dev/ui/figures/animation-feature.gif new file mode 100644 index 0000000000000000000000000000000000000000..f75ac924799af38dbfe43c2c2e5572fb0e3c09d0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/animation-feature.gif differ diff --git a/zh-cn/application-dev/ui/figures/animation-feature1.gif b/zh-cn/application-dev/ui/figures/animation-feature1.gif new file mode 100644 index 0000000000000000000000000000000000000000..5dc236ba194e59fd46416ca0a738ed7139a59374 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/animation-feature1.gif differ diff --git a/zh-cn/application-dev/ui/figures/blank.gif b/zh-cn/application-dev/ui/figures/blank.gif new file mode 100644 index 0000000000000000000000000000000000000000..879f53781ff9f9087d3343cd867be8d56deeca1e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/blank.gif differ diff --git a/zh-cn/application-dev/ui/figures/breakpoints.gif b/zh-cn/application-dev/ui/figures/breakpoints.gif new file mode 100644 index 0000000000000000000000000000000000000000..f2e18ecafe8202705a34e6c76b4fdc59d5cca8d6 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/breakpoints.gif differ diff --git a/zh-cn/application-dev/ui/figures/column.png b/zh-cn/application-dev/ui/figures/column.png new file mode 100644 index 0000000000000000000000000000000000000000..27321b5a24798d6d423cbf76eab974f4ebc2d0fb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/column.png differ diff --git a/zh-cn/application-dev/ui/figures/columnGap.png b/zh-cn/application-dev/ui/figures/columnGap.png new file mode 100644 index 0000000000000000000000000000000000000000..1b7017a280158e88baabca3dfd1e77c6068c4655 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnGap.png differ diff --git a/zh-cn/application-dev/ui/figures/columnTemplate.png b/zh-cn/application-dev/ui/figures/columnTemplate.png new file mode 100644 index 0000000000000000000000000000000000000000..730abeccaffa22f88e916fb199cbc1e44a982789 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnTemplate.png differ diff --git a/zh-cn/application-dev/ui/figures/columnalign.png b/zh-cn/application-dev/ui/figures/columnalign.png new file mode 100644 index 0000000000000000000000000000000000000000..a73a28a23c3719aee5379e0c8b3f9cc3627ca3e2 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnalign.png differ diff --git a/zh-cn/application-dev/ui/figures/columnjustify.png b/zh-cn/application-dev/ui/figures/columnjustify.png new file mode 100644 index 0000000000000000000000000000000000000000..34e68343a8b621f4a0567ea9424169f6a7e5ef1b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnjustify.png differ diff --git a/zh-cn/application-dev/ui/figures/columns1.png b/zh-cn/application-dev/ui/figures/columns1.png new file mode 100644 index 0000000000000000000000000000000000000000..f7e2c38a9b5f22ebf44eaae8eb9fea461d198018 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns1.png differ diff --git a/zh-cn/application-dev/ui/figures/columns2.png b/zh-cn/application-dev/ui/figures/columns2.png new file mode 100644 index 0000000000000000000000000000000000000000..5e549b42338ffe87b944807cec7e57144b5cbe74 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns2.png differ diff --git a/zh-cn/application-dev/ui/figures/columns3.gif b/zh-cn/application-dev/ui/figures/columns3.gif new file mode 100644 index 0000000000000000000000000000000000000000..e44df1b36066095ed6e8741e26d9f04a4c9a2b0b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns3.gif differ diff --git a/zh-cn/application-dev/ui/figures/columnspace.png b/zh-cn/application-dev/ui/figures/columnspace.png new file mode 100644 index 0000000000000000000000000000000000000000..6af047e34c3e1e2ecd8d3d1d99af17ca01c5b58b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnspace.png differ diff --git a/zh-cn/application-dev/ui/figures/component.PNG b/zh-cn/application-dev/ui/figures/component.PNG new file mode 100644 index 0000000000000000000000000000000000000000..bf949004e64004c9ac3f24f6edbd625b135c9717 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/component.PNG differ diff --git a/zh-cn/application-dev/ui/figures/component.gif b/zh-cn/application-dev/ui/figures/component.gif new file mode 100644 index 0000000000000000000000000000000000000000..e50a590ed7049a3c52149d10886e5b38ffdae2a5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/component.gif differ diff --git a/zh-cn/application-dev/ui/figures/crossCenter.png b/zh-cn/application-dev/ui/figures/crossCenter.png new file mode 100644 index 0000000000000000000000000000000000000000..5efa144a653649d5118edf3790c8e26b370c49df Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossCenter.png differ diff --git a/zh-cn/application-dev/ui/figures/crossEnd.png b/zh-cn/application-dev/ui/figures/crossEnd.png new file mode 100644 index 0000000000000000000000000000000000000000..2330225d2b046b67c30c040a4a72e2e553e0c824 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossEnd.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpacearound.png b/zh-cn/application-dev/ui/figures/crossSpacearound.png new file mode 100644 index 0000000000000000000000000000000000000000..280987579ef8c11a847d6842e9596168aec97cdb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpacearound.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpacebetween.png b/zh-cn/application-dev/ui/figures/crossSpacebetween.png new file mode 100644 index 0000000000000000000000000000000000000000..65e408eb2fde074f1a9e65dfff01de8e569ccf66 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpacebetween.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpaceevenly.png b/zh-cn/application-dev/ui/figures/crossSpaceevenly.png new file mode 100644 index 0000000000000000000000000000000000000000..83f3a801a8f79d06794680db0309a9fa5fee1387 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpaceevenly.png differ diff --git a/zh-cn/application-dev/ui/figures/crossStart.png b/zh-cn/application-dev/ui/figures/crossStart.png new file mode 100644 index 0000000000000000000000000000000000000000..1f323600a999f2ca313a5a5273088620f72578c3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossStart.png differ diff --git a/zh-cn/application-dev/ui/figures/customLayout.png b/zh-cn/application-dev/ui/figures/customLayout.png new file mode 100644 index 0000000000000000000000000000000000000000..1231a0e0e693e1648c06b25898596bdc8546a3e0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/customLayout.png differ diff --git a/zh-cn/application-dev/ui/figures/direction.png b/zh-cn/application-dev/ui/figures/direction.png new file mode 100644 index 0000000000000000000000000000000000000000..702c9b07fa00b8685415bb83879ead774001ee56 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction.png differ diff --git a/zh-cn/application-dev/ui/figures/direction1.png b/zh-cn/application-dev/ui/figures/direction1.png new file mode 100644 index 0000000000000000000000000000000000000000..1153aade7a6764fe871d63783abdcd09366fba13 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction1.png differ diff --git a/zh-cn/application-dev/ui/figures/direction2.png b/zh-cn/application-dev/ui/figures/direction2.png new file mode 100644 index 0000000000000000000000000000000000000000..e0a74253389934179d0cbcbaf4a43c01df18f7e5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction2.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature.png b/zh-cn/application-dev/ui/figures/drawing-feature.png new file mode 100644 index 0000000000000000000000000000000000000000..c1468667bdf74b80629c1eaa32cbef935ea5048c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature1.png b/zh-cn/application-dev/ui/figures/drawing-feature1.png new file mode 100644 index 0000000000000000000000000000000000000000..6b3ca4fa90e25b5906bdadcdcbf134bd00b7b34b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature1.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature2.png b/zh-cn/application-dev/ui/figures/drawing-feature2.png new file mode 100644 index 0000000000000000000000000000000000000000..42fc7cdf9436680a30413c5bb07e02fd3230ec0c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature2.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature3.png b/zh-cn/application-dev/ui/figures/drawing-feature3.png new file mode 100644 index 0000000000000000000000000000000000000000..c090ff948d7333f3dea17dd7ec54488638788c0c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature3.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature4.png b/zh-cn/application-dev/ui/figures/drawing-feature4.png new file mode 100644 index 0000000000000000000000000000000000000000..bcfee4728b4d5fc9bfc57e6bb743e708ad0b2379 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature4.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature5.png b/zh-cn/application-dev/ui/figures/drawing-feature5.png new file mode 100644 index 0000000000000000000000000000000000000000..e70c63ed2f601cf4cd30f319dc6ebd74f216c909 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature5.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature6.png b/zh-cn/application-dev/ui/figures/drawing-feature6.png new file mode 100644 index 0000000000000000000000000000000000000000..772bd122cd1ecb252625f59af5ea3e5ff61689fc Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature6.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature7.png b/zh-cn/application-dev/ui/figures/drawing-feature7.png new file mode 100644 index 0000000000000000000000000000000000000000..c77366f46008f173bc117f95bed6bc7827af11cd Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature7.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature8.png b/zh-cn/application-dev/ui/figures/drawing-feature8.png new file mode 100644 index 0000000000000000000000000000000000000000..17cdf2ba3b6e3eeabbe93ed3115c34801634ba8e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature8.png differ diff --git a/zh-cn/application-dev/ui/figures/flex.png b/zh-cn/application-dev/ui/figures/flex.png new file mode 100644 index 0000000000000000000000000000000000000000..848ceef3873ed6f83466d9ab42f6aa68cb341fe9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flex.png differ diff --git a/zh-cn/application-dev/ui/figures/flex1.PNG b/zh-cn/application-dev/ui/figures/flex1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..cb125f009c7473782b463689466708d49ae474e0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flex1.PNG differ diff --git a/zh-cn/application-dev/ui/figures/flexExample.png b/zh-cn/application-dev/ui/figures/flexExample.png new file mode 100644 index 0000000000000000000000000000000000000000..73d4e3407dad6422e640dc8a27a4347c2c73dd9d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexExample.png differ diff --git a/zh-cn/application-dev/ui/figures/flexbasis.png b/zh-cn/application-dev/ui/figures/flexbasis.png new file mode 100644 index 0000000000000000000000000000000000000000..df26a3272410052e3df94b2c4207015d5d23b613 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexbasis.png differ diff --git a/zh-cn/application-dev/ui/figures/flexgrow.png b/zh-cn/application-dev/ui/figures/flexgrow.png new file mode 100644 index 0000000000000000000000000000000000000000..9c2b84e0e070e67613504dcb52ea02acb6ed72b9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexgrow.png differ diff --git a/zh-cn/application-dev/ui/figures/flexshrink.png b/zh-cn/application-dev/ui/figures/flexshrink.png new file mode 100644 index 0000000000000000000000000000000000000000..20ddfe6941c5313b1054f1d479da8b24014c3928 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexshrink.png differ diff --git a/zh-cn/application-dev/ui/figures/gridExp1.png b/zh-cn/application-dev/ui/figures/gridExp1.png new file mode 100644 index 0000000000000000000000000000000000000000..6767d92cee335418b9c82aa842359dfce1d887c9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridExp1.png differ diff --git a/zh-cn/application-dev/ui/figures/gridExp2.png b/zh-cn/application-dev/ui/figures/gridExp2.png new file mode 100644 index 0000000000000000000000000000000000000000..c484c27c079f3490b32d7e6c2c8e3f0b84a0151a Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridExp2.png differ diff --git a/zh-cn/application-dev/ui/figures/griditem.png b/zh-cn/application-dev/ui/figures/griditem.png new file mode 100644 index 0000000000000000000000000000000000000000..9560e2291add8a9117be6a5ccb90033b960190d5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/griditem.png differ diff --git a/zh-cn/application-dev/ui/figures/gridlayout.png b/zh-cn/application-dev/ui/figures/gridlayout.png new file mode 100644 index 0000000000000000000000000000000000000000..cc0db8ce530d60191adf8ffaefdbf11b97305067 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridlayout.png differ diff --git a/zh-cn/application-dev/ui/figures/gutter1.png b/zh-cn/application-dev/ui/figures/gutter1.png new file mode 100644 index 0000000000000000000000000000000000000000..3b246c32f1079b06c18c1a14cbcb286c241a8623 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gutter1.png differ diff --git a/zh-cn/application-dev/ui/figures/gutter2.png b/zh-cn/application-dev/ui/figures/gutter2.png new file mode 100644 index 0000000000000000000000000000000000000000..534c169420509639cf21b30b41d65ccb34758b66 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gutter2.png differ diff --git a/zh-cn/application-dev/ui/figures/isVisible.gif b/zh-cn/application-dev/ui/figures/isVisible.gif new file mode 100644 index 0000000000000000000000000000000000000000..bdb7b5ae5fe49adfaf4eb48c1533e4fe599be612 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/isVisible.gif differ diff --git a/zh-cn/application-dev/ui/figures/justifyContent.png b/zh-cn/application-dev/ui/figures/justifyContent.png new file mode 100644 index 0000000000000000000000000000000000000000..2e997f9cba6ce5c2ad93c1f2e33728b7db17bdd3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/justifyContent.png differ diff --git a/zh-cn/application-dev/ui/figures/layoutWeight.gif b/zh-cn/application-dev/ui/figures/layoutWeight.gif new file mode 100644 index 0000000000000000000000000000000000000000..b7d0cdeeb268f96427c67daeb1673c5ec1b55ed0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/layoutWeight.gif differ diff --git a/zh-cn/application-dev/ui/figures/lifecycle.PNG b/zh-cn/application-dev/ui/figures/lifecycle.PNG new file mode 100644 index 0000000000000000000000000000000000000000..a9b5769ad867f880dbe2b746b15de80cadbf799e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/lifecycle.PNG differ diff --git a/zh-cn/application-dev/ui/figures/list1.gif b/zh-cn/application-dev/ui/figures/list1.gif new file mode 100644 index 0000000000000000000000000000000000000000..f421df651539da975e30d2294598e587e44d665e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/list1.gif differ diff --git a/zh-cn/application-dev/ui/figures/list2.gif b/zh-cn/application-dev/ui/figures/list2.gif new file mode 100644 index 0000000000000000000000000000000000000000..97d8e42b844537f19ec1fab10aca7af58a45c0a4 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/list2.gif differ diff --git a/zh-cn/application-dev/ui/figures/listcolumn.gif b/zh-cn/application-dev/ui/figures/listcolumn.gif new file mode 100644 index 0000000000000000000000000000000000000000..4c0d4453b6e8d1207452e65d47c4867d77206115 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/listcolumn.gif differ diff --git a/zh-cn/application-dev/ui/figures/listrow.gif b/zh-cn/application-dev/ui/figures/listrow.gif new file mode 100644 index 0000000000000000000000000000000000000000..16b77e79d3288a84b47feb7b99beac0392a2e4f5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/listrow.gif differ diff --git a/zh-cn/application-dev/ui/figures/mainCenter.png b/zh-cn/application-dev/ui/figures/mainCenter.png new file mode 100644 index 0000000000000000000000000000000000000000..30aa156d5ab296c25e30958cbd3f83ac35de88d1 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainCenter.png differ diff --git a/zh-cn/application-dev/ui/figures/mainEnd.png b/zh-cn/application-dev/ui/figures/mainEnd.png new file mode 100644 index 0000000000000000000000000000000000000000..fea2431892d09a06f067b438ae9462a09ad97ed0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainEnd.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpacearound.png b/zh-cn/application-dev/ui/figures/mainSpacearound.png new file mode 100644 index 0000000000000000000000000000000000000000..0398af5f8f1a4dece7057ec3b1a852e1518933ef Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpacearound.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpacebetween.png b/zh-cn/application-dev/ui/figures/mainSpacebetween.png new file mode 100644 index 0000000000000000000000000000000000000000..d230aa1e735c0964581d1cf17d18af5152a5b466 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpacebetween.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpaceevenly.png b/zh-cn/application-dev/ui/figures/mainSpaceevenly.png new file mode 100644 index 0000000000000000000000000000000000000000..d22917514351643139709069af9f78419be7c748 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpaceevenly.png differ diff --git a/zh-cn/application-dev/ui/figures/mainStart.png b/zh-cn/application-dev/ui/figures/mainStart.png new file mode 100644 index 0000000000000000000000000000000000000000..207577b642507badc1b8064ab2f75c51130e58dd Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainStart.png differ diff --git a/zh-cn/application-dev/ui/figures/offset.gif b/zh-cn/application-dev/ui/figures/offset.gif new file mode 100644 index 0000000000000000000000000000000000000000..13d5614f4cfa0ede034e44f9fc333b1d55e891ff Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset.gif differ diff --git a/zh-cn/application-dev/ui/figures/offset1.png b/zh-cn/application-dev/ui/figures/offset1.png new file mode 100644 index 0000000000000000000000000000000000000000..e760daef7809d60e1c7b9323bffc267f592c8fc5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset1.png differ diff --git a/zh-cn/application-dev/ui/figures/offset2.gif b/zh-cn/application-dev/ui/figures/offset2.gif new file mode 100644 index 0000000000000000000000000000000000000000..b517e892ed6ff4ad337e57d044aa518ff78a8792 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset2.gif differ diff --git a/zh-cn/application-dev/ui/figures/order1.png b/zh-cn/application-dev/ui/figures/order1.png new file mode 100644 index 0000000000000000000000000000000000000000..297dea381d85074e91edfb664bac5b8e3151f7bb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/order1.png differ diff --git a/zh-cn/application-dev/ui/figures/order2.gif b/zh-cn/application-dev/ui/figures/order2.gif new file mode 100644 index 0000000000000000000000000000000000000000..315c82e417d240d0624a8206c9adf47c4c0a3ec3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/order2.gif differ diff --git a/zh-cn/application-dev/ui/figures/position.gif b/zh-cn/application-dev/ui/figures/position.gif new file mode 100644 index 0000000000000000000000000000000000000000..67811987caa4b35beaea64da68e7d3786db52a58 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/position.gif differ diff --git a/zh-cn/application-dev/ui/figures/row.png b/zh-cn/application-dev/ui/figures/row.png new file mode 100644 index 0000000000000000000000000000000000000000..d7fced9fe4a9fc618dee88ae95cc2f04a34bb3c3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/row.png differ diff --git a/zh-cn/application-dev/ui/figures/rowalign.png b/zh-cn/application-dev/ui/figures/rowalign.png new file mode 100644 index 0000000000000000000000000000000000000000..1f87579bb75ea031951dc073f0cd0a3a65698ee6 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowalign.png differ diff --git a/zh-cn/application-dev/ui/figures/rowjustify.png b/zh-cn/application-dev/ui/figures/rowjustify.png new file mode 100644 index 0000000000000000000000000000000000000000..7ed6dfc34d5c3dee1202925b373d5c7b7928c248 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowjustify.png differ diff --git a/zh-cn/application-dev/ui/figures/rowspace.png b/zh-cn/application-dev/ui/figures/rowspace.png new file mode 100644 index 0000000000000000000000000000000000000000..9bf2d2da0b1634d8051214908b83bc5e41f1702d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowspace.png differ diff --git a/zh-cn/application-dev/ui/figures/scrollcolumn.gif b/zh-cn/application-dev/ui/figures/scrollcolumn.gif new file mode 100644 index 0000000000000000000000000000000000000000..80ee68958c80502be31ddcecc22f198c14a4c335 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/scrollcolumn.gif differ diff --git a/zh-cn/application-dev/ui/figures/scrollrow.gif b/zh-cn/application-dev/ui/figures/scrollrow.gif new file mode 100644 index 0000000000000000000000000000000000000000..14f3d25cbf137366ce3c2bb93f683d75a9297597 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/scrollrow.gif differ diff --git a/zh-cn/application-dev/ui/figures/span1.png b/zh-cn/application-dev/ui/figures/span1.png new file mode 100644 index 0000000000000000000000000000000000000000..fe59d441c386189694b3185e23279f14c6dd4a97 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/span1.png differ diff --git a/zh-cn/application-dev/ui/figures/span2.gif b/zh-cn/application-dev/ui/figures/span2.gif new file mode 100644 index 0000000000000000000000000000000000000000..eba3ab4a41c44642c47f1864858094771043dcc7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/span2.gif differ diff --git a/zh-cn/application-dev/ui/figures/stack1.png b/zh-cn/application-dev/ui/figures/stack1.png new file mode 100644 index 0000000000000000000000000000000000000000..87574a9c72652fdda57f54405b675b622f804479 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stack1.png differ diff --git a/zh-cn/application-dev/ui/figures/stack2.png b/zh-cn/application-dev/ui/figures/stack2.png new file mode 100644 index 0000000000000000000000000000000000000000..6a518ad4ac87cc91ef44894d15774cb3d60568d1 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stack2.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottom.png b/zh-cn/application-dev/ui/figures/stackbottom.png new file mode 100644 index 0000000000000000000000000000000000000000..d4a1d76611bb608becded581f24b69b48185d96d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottom.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottomend.png b/zh-cn/application-dev/ui/figures/stackbottomend.png new file mode 100644 index 0000000000000000000000000000000000000000..6f34877f2ed88390eca31bab2370c187d012fd73 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottomend.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottomstart.png b/zh-cn/application-dev/ui/figures/stackbottomstart.png new file mode 100644 index 0000000000000000000000000000000000000000..d6539785544de70d20ce382465974cfb24d955c7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottomstart.png differ diff --git a/zh-cn/application-dev/ui/figures/stackcenter.png b/zh-cn/application-dev/ui/figures/stackcenter.png new file mode 100644 index 0000000000000000000000000000000000000000..0ba76abeba693ae3d1654b6b3fbde91661669237 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackcenter.png differ diff --git a/zh-cn/application-dev/ui/figures/stackend.png b/zh-cn/application-dev/ui/figures/stackend.png new file mode 100644 index 0000000000000000000000000000000000000000..2bf91c717a94ce47a2f3c9ca766eb89fae513a71 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackend.png differ diff --git a/zh-cn/application-dev/ui/figures/stackstart.png b/zh-cn/application-dev/ui/figures/stackstart.png new file mode 100644 index 0000000000000000000000000000000000000000..3936627a8d4134acd3e02833cb2c3c593f52c66e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackstart.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktop.png b/zh-cn/application-dev/ui/figures/stacktop.png new file mode 100644 index 0000000000000000000000000000000000000000..01a649049c24df96510727918689455ad9898559 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktop.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktopend.png b/zh-cn/application-dev/ui/figures/stacktopend.png new file mode 100644 index 0000000000000000000000000000000000000000..95e8fef4f2c2a6905ed0efc00e9cacd14852c5de Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktopend.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktopstart.png b/zh-cn/application-dev/ui/figures/stacktopstart.png new file mode 100644 index 0000000000000000000000000000000000000000..7b742984076e7066cca56a5647bfa3c096b317f2 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktopstart.png differ diff --git a/zh-cn/application-dev/ui/figures/width.gif b/zh-cn/application-dev/ui/figures/width.gif new file mode 100644 index 0000000000000000000000000000000000000000..34007100b438eb6fc47dd5f48eda6033bc759412 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/width.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif new file mode 100644 index 0000000000000000000000000000000000000000..aac78d2abe528a9781e7e07ed2e46a4bf56d7891 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif new file mode 100644 index 0000000000000000000000000000000000000000..a7d9b572abb833cc7cd52e63d25c4c261a10af65 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png new file mode 100644 index 0000000000000000000000000000000000000000..25330d63162d9999d2c57d3c33bcc20731df7851 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png index 5accde8bbb1146e3bade9d6cc4d35127dd58b86f..67b8d1571853fe13079a13ed32aff66bc2fc4452 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png index b6045521e10cf66733222c0b85b1b65dd20cb66f..ddf24cd804055371cbd8a753089263f6bcc32b79 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png index 546fb29b1f18573353d11d5515f444bf720fcf52..9c89860f26331dc11cf8104711be1ad3be918111 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png index a6d0026ba316551ff0819493b84ae8c9cb063289..f910230ebfab9c5315eb1c2bc99f0ca35b3cbe23 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif index 0173419db3fd06cc5d328dd6931a2c76664f4596..b59ae3d79b2bc926634a50c1f3f6aecce247763c 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif index 26152ef9f22387729561bdddb9fa7d50019e08cb..c88150c77afccf736d42fe7253df27f2b1d27cd5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png new file mode 100644 index 0000000000000000000000000000000000000000..2441a46f00b3083dfaa8ec2dcdb1760aa7e2aeb7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif index b07f4a9f456b5bccab8fe2a2dc997818efad5ddb..a7d9b572abb833cc7cd52e63d25c4c261a10af65 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png index f6b70b8f1ef886bf8ed6f26e148bddee0b163fd5..60160d18d66fef9a5b65a4c5675fe91873e95582 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png index a84303ae2d68affe3f5702317d9f2bf951c90698..b775a2bf408dd710861afa0dfa9f756d5181e811 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png index d0e9cf658b9b396873f24666945bb796384c2041..b27a7f5358c954fe7e1bd912358d29d456870c2a 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png index 767315d2f69278028746341e79f88ad179930338..b60416b59cb77e096d615ba1b25d2b14056abe00 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png index 653da4be405165f59cbbe570e9d4d64747fa7495..3f2f15792563ec89015abce1fcf30248b3c0288e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png index aaa0cbf699a302616ce142f43ea3b96df99d75ac..18abb7b725fcf0172f189c0f1cf70e9c5ae31642 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png index fb85274edcd9b0a66eaa9e3da3b77e543c048cc8..6a845d64a542809c05f008eef5d1e1ed9d1c22a5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png index 49182b6d8f1c96dcbaac493179fdab3d4b9a7bd4..0a53a5742ac5fda3501a93f576b945e21bd2addf 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png index 2923d13dcf52b856158b440de03df929abc4955b..c508bb8764c28f228e2c0a33dd6ee97e48dfe682 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif index 8e9c75334361806ac822c8c0f2c377c1679c6ca3..aac78d2abe528a9781e7e07ed2e46a4bf56d7891 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png new file mode 100644 index 0000000000000000000000000000000000000000..68b537c0afc28896fc8d14d36a5d7190fcfa256c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png differ diff --git a/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md b/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md deleted file mode 100644 index 86db59447ccb15bad9579553a1eef2e03e143d23..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md +++ /dev/null @@ -1,97 +0,0 @@ -# 组件创建和重新初始化 - -## 初始创建和渲染 - -1. 创建父组件ParentComp; - -2. 本地初始化ParentComp的状态变量isCountDown; - -3. 执行ParentComp的build函数; - -4. 创建Column内置组件; - 1. 创建Text内置组件,设置其文本展示内容,并将Text组件实例添加到Column中; - 2. 判断if条件,创建true分支上的组件; - 1. 创建Image内置组件,并设置其图片源地址; - 2. 使用给定的构造函数创建TimerComponent; - 1. 创建TimerComponent对象; - 2. 本地初始化成员变量初始值; - 3. 使用TimerComponent构造函数提供的参数更新成员变量的值; - 4. 执行TimerComponent的aboutToAppear函数; - 5. 执行TimerComponent的build函数,创建相应的UI描述结构; - 3. 创建Button内置组件,设置相应的内容。 - - -## 状态更新 - -用户单击按钮时: - -1. ParentComp的isCountDown状态变量的值更改为false; - -2. 执行ParentComp的build函数; - -3. Column内置组件会被框架重用并执行重新初始化; - -4. Column的子组件会重用内存中的对象,但会进行重新初始化; - 1. Text内置组件会被重用,但使用新的文本内容进行重新初始化; - 2. 判断if条件,使用false分支上的组件; - 1. 原来true分支上的组件不在使用,这些组件会进行销毁; - 1. 创建的Image内置组件实例进行销毁; - 2. TimerComponent组件实例进行销毁,aboutToDisappear函数被调用; - 2. 创建false分支上的组件; - 1. 创建Image内置组件,并设置其图片源地址; - 2. 使用给定的构造函数重新创建TimerComponent; - 3. 新创建的TimerComponent进行初始化,并调用aboutToAppear函数和build函数。 - 3. Button内置组件会被重用,但使用新的图片源地址。 - - -## 示例 - -```ts -// xxx.ets -@Entry -@Component -struct ParentComp { - @State isCountDown: boolean = true - build() { - Column() { - Text(this.isCountDown ? 'Count Down' : 'Stopwatch') - if (this.isCountDown) { - Image($r("app.media.countdown")).width(200).height(200) - TimerComponent({counter: 10, changePerSec: -1, showInColor: Color.Red}) - } else { - Image($r("app.media.stopwatch")).width(200).height(200) - TimerComponent({counter: 0, changePerSec: +1, showInColor: Color.Black }) - } - Button(this.isCountDown ? 'Switch to Stopwatch' : 'Switch to Count Down') - .onClick(() => {this.isCountDown = !this.isCountDown}) - } - } -} - -// Manage and display a count down / stop watch timer -@Component -struct TimerComponent { - @State counter: number = 0 - private changePerSec: number = -1 - private showInColor: Color = Color.Black - private timerId : number = -1 - - build() { - Text(`${this.counter}sec`) - .fontColor(this.showInColor) - } - - aboutToAppear() { - this.timerId = setInterval(() => {this.counter += this.changePerSec}, 1000) - } - - aboutToDisappear() { - if (this.timerId > 0) { - clearTimeout(this.timerId) - this.timerId = -1 - } - } -} -``` - -![](figures/zh-cn_image_0000001118642023.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ts-custom-component-initialization.md b/zh-cn/application-dev/ui/ts-custom-component-initialization.md deleted file mode 100644 index 1433542af3203e3a54f6d883ef099b8f5438f52f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-custom-component-initialization.md +++ /dev/null @@ -1,125 +0,0 @@ -# 自定义组件成员变量初始化 - -组件的成员变量可以通过两种方式初始化: - - -- 本地初始化,例如: - ```ts - @State counter: Counter = new Counter() - ``` - -- 在构造组件时通过构造参数初始化,例如: - ```ts - MyComponent({counter: $myCounter}) - ``` - - -具体允许哪种方式取决于状态变量的装饰器: - - -| 装饰器类型 | 本地初始化 | 通过构造函数参数初始化 | -| ------------ | ----- | ----------- | -| @State | 必须 | 可选 | -| @Prop | 禁止 | 必须 | -| @Link | 禁止 | 必须 | -| @StorageLink | 必须 | 禁止 | -| @StorageProp | 必须 | 禁止 | -| @Provide | 必须 | 可选 | -| @Consume | 禁止 | 禁止 | -| @ObjectLink | 禁止 | 必须 | -| 常规成员变量 | 推荐 | 可选 | - - -从上表中可以看出: - - -- @State变量需要本地初始化,初始化的值可以被构造参数覆盖; - -- @Prop和@Link变量必须且仅通过构造函数参数进行初始化。 - - -通过构造函数方法初始化成员变量,需要遵循如下规则: - - -| 从父组件中的变量(下)到子组件中的变量(右) | @State | @Link | @Prop | 常规变量 | -| ---------------------- | ------ | ----- | ----- | ---- | -| @State | 不允许 | 允许 | 允许 | 允许 | -| @Link | 不允许 | 允许 | 不推荐 | 允许 | -| @Prop | 不允许 | 不允许 | 允许 | 允许 | -| @StorageLink | 不允许 | 允许 | 不允许 | 允许 | -| @StorageProp | 不允许 | 不允许 | 不允许 | 允许 | -| 常规变量 | 允许 | 不允许 | 不允许 | 允许 | - - -从上表中可以看出: - - -- 父组件的常规变量可以用于初始化子组件的@State变量,但不能用于初始化@Link或@Prop变量。 - -- 父组件的@State变量可以初始化子组件的@Prop、@Link(通过$)或常规变量,但不能初始化子组件的@State变量。 - -- 父组件的@Link变量可以初始化子组件的@Link或常规变量。但是初始化子组件的@State成员是语法错误,此外不建议初始化@prop。 - -- 父组件的@Prop变量可以初始化子组件的常规变量或@Prop变量,但不能初始化子组件的@State或@Link变量。 - -- @StorageLink和@StorageProp不允许由父组件中传递到子组件。 - -- 除了上述规则外,还需要遵循TS的强类型规则。 - - -## 示例 - -```ts -// xxx.ets -class ClassA { - public a:number - constructor(a: number) { - this.a = a - } -} -@Entry -@Component -struct Parent { - @State parentState: ClassA = new ClassA(1) - - build() { - Column() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aState: new ClassA(2), aLink: $parentState }) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aLink: $parentState }) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aState: new ClassA(3), aLink: $parentState }) - } - } - } -} - -@Component -struct CompA { - @State aState: any = false - @Link aLink: ClassA - - build() { - Column() { - CompB({ bLink: $aLink, bProp: this.aState }) - CompB({ bLink: $aState, bProp: false }) - } - } -} - -@Component -struct CompB { - @Link bLink: ClassA - @Prop bProp: boolean - - build() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - Text(JSON.stringify(this.bLink.a)).fontSize(30) - Text(JSON.stringify(this.bProp)).fontSize(30).fontColor(Color.Red) - }.margin(10) - } -} -``` diff --git a/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md b/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md deleted file mode 100644 index 5a0126b00ae83f1e41792a2d60aa5032e5131525..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md +++ /dev/null @@ -1,57 +0,0 @@ -# 自定义组件生命周期回调函数 - -自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。 - - -## 生命周期回调函数定义 - -| 函数名 | 描述 | -| ---------------- | ------------------------------------------------------------ | -| aboutToAppear | 函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。 | -| aboutToDisappear | 函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。 | -| onPageShow | 页面每次显示时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 | -| onPageHide | 页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 | -| onBackPress | 当用户点击返回按钮时触发,仅\@Entry修饰的自定义组件生效。
- 返回true表示页面自己处理返回逻辑, 不进行页面路由。
- 返回false表示使用默认的返回逻辑。
- 不返回值会作为false处理。 | -| onMeasure9+ | 框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量 | -| onLayout9+ | 框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量 | - - -## 示例 - -```ts -// xxx.ets -@Entry -@Component -struct CountDownTimerComponent { - @State countDownFrom: number = 10 - private timerId: number = -1 - - aboutToAppear(): void { - this.timerId = setInterval(() => { - if (this.countDownFrom <= 1) { - clearTimeout(this.timerId) - } - this.countDownFrom -= 1 - }, 1000) // decr counter by 1 every second - } - - aboutToDisappear(): void { - if (this.timerId > 0) { - clearTimeout(this.timerId) - this.timerId = -1 - } - } - - build() { - Text(`${this.countDownFrom} sec left`) - } -} -``` - -上述示例表明,生命周期函数对于允许CountDownTimerComponent管理其计时器资源至关重要,类似的函数也包括异步从网络请求加载资源。 - - -> **说明:** -> - 允许在生命周期函数中使用Promise和异步回调函数,比如网络资源获取,定时器设置等; -> -> - 不允许在生命周期函数中使用async await。 diff --git a/zh-cn/application-dev/ui/ts-framework-directory.md b/zh-cn/application-dev/ui/ts-framework-directory.md deleted file mode 100644 index b20e3023475a0ced28afa89fb94ad2f02a75e077..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-framework-directory.md +++ /dev/null @@ -1,38 +0,0 @@ -# 目录结构 - - -FA应用的ArkTS模块(entry/src/main)的典型开发目录结构如下: - - -![zh-cn_image_0000001182200571](figures/zh-cn_image_0000001182200571.png) - - -**目录结构中文件分类如下:** - - -.ets结尾的ArkTS文件,用于描述UI布局、样式、事件交互和页面逻辑。 - -**各个文件夹和文件的作用:** - -- **app.ets**文件用于全局应用逻辑和应用生命周期管理。 - -- **pages**目录用于存放所有页面。 - -- **common**目录用于存放公共代码文件,比如:自定义组件和公共方法。 - - -> **说明:** -> -> - 资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源文件的分类](ui-ts-basic-resource-file-categories.md)。 ->- 页面支持导入TypeScript和JavaScript文件。 - -**js标签配置:** - - 开发框架需要在配置文件中标识相关的js标签,其中的每个元素代表一个JS模块的信息,包含了实例名称、页面路由、视图窗口等。 - - -> **说明:** -> -> FA模型请参考 [表22 js对象的内部结构说明](../quick-start/package-structure.md#module对象的内部结构)。 -> -> Stage模型请参考 [表3 module对象内部结构说明](../quick-start/stage-structure.md#module对象内部结构)。 diff --git a/zh-cn/application-dev/ui/ts-resource-access.md b/zh-cn/application-dev/ui/ts-resource-access.md deleted file mode 100644 index a2ea1141108398203160e8fa752d1cc4727c5889..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-resource-access.md +++ /dev/null @@ -1,154 +0,0 @@ -# 资源访问 - - -## 访问应用资源 - -在工程中,通过```"$r('app.type.name')"```的形式引用应用资源。app代表是应用内resources目录中定义的资源;type代表资源类型(或资源的存放位置),可以取“color”、“float”、“string”、“plural”、“media”,name代表资源命名,由开发者定义资源时确定。 - -引用rawfile下资源时使用```"$rawfile('filename')"```的形式,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。 - -> **说明:** -> -> 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。 -> -> `$r`返回值为Resource对象,可通过[getString](../reference/apis/js-apis-resource-manager.md#getstring) 方法获取对应的字符串。 - -在xxx.ets文件中,可以使用在resources目录中定义的资源。 - -```ts -Text($r('app.string.string_hello')) - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} - -Text($r('app.string.string_world')) - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) -} - -Text($r('app.string.message_arrive', "five of the clock")) // 引用string资源,$r的第二个参数用于替换%s - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} - -Text($r('app.plural.eat_apple', 5, 5)) // plural$r引用,第一个指定plural资源,第二个参数指定单复数的数量,此处第三个数字为对%d的替换 - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) -} - -Image($r('app.media.my_background_image')) // media资源的$r引用 - -Image($rawfile('test.png')) // rawfile$r引用rawfile目录下图片 - -Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下图片 -``` -## 访问系统资源 - -系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。 - - -开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。 - -```ts -Text('Hello') - .fontColor($r('sys.color.ohos_id_color_emphasize')) - .fontSize($r('sys.float.ohos_id_text_size_headline1')) - .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) - .backgroundColor($r('sys.color.ohos_id_color_palette_aux1')) -Image($r('sys.media.ohos_app_icon')) - .border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2}) - .margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')}) - .height(200) - .width(300) -``` -## 资源文件示例 - -color.json文件的内容如下: - - -```json -{ - "color": [ - { - "name": "color_hello", - "value": "#ffff0000" - }, - { - "name": "color_world", - "value": "#ff0000ff" - } - ] -} -``` - -float.json文件的内容如下: - - -```json -{ - "float":[ - { - "name":"font_hello", - "value":"28.0fp" - }, - { - "name":"font_world", - "value":"20.0fp" - } - ] -} -``` - -string.json文件的内容如下: - - -```json -{ - "string":[ - { - "name":"string_hello", - "value":"Hello" - }, - { - "name":"string_world", - "value":"World" - }, - { - "name":"message_arrive", - "value":"We will arrive at %s." - } - ] -} -``` - -plural.json文件的内容如下: - - -```json -{ - "plural":[ - { - "name":"eat_apple", - "value":[ - { - "quantity":"one", - "value":"%d apple" - }, - { - "quantity":"other", - "value":"%d apples" - } - ] - } - ] -} -``` - - - - -## 相关实例 - -针对访问应用资源,有以下相关实例可供参考: - -- [`ResourceManager`:资源管理器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager) diff --git a/zh-cn/application-dev/ui/ui-ts-animation-feature.md b/zh-cn/application-dev/ui/ui-ts-animation-feature.md new file mode 100644 index 0000000000000000000000000000000000000000..16869cea7b746874566257d31d4e9448d0a3967f --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-animation-feature.md @@ -0,0 +1,343 @@ +# 添加动画效果 + +动画主要包含了组件动画和页面间动画,并提供了[插值计算](../reference/apis/js-apis-curve.md)和[矩阵变换](../reference/apis/js-apis-matrix4.md)的动画能力接口,让开发者极大程度的自主设计动画效果。 + +在本节主要完成两个动画效果: + +1. 启动页的闪屏动画,即Logo图标的渐出和放大效果; +2. 食物列表页和食物详情页的共享元素转场动画效果。 + +## animateTo实现闪屏动画 + +组件动画包括属性动画和animateTo显式动画: + +1. 属性动画:设置组件通用属性变化的动画效果。 +2. 显式动画:设置组件从状态A到状态B的变化动画效果,包括样式、位置信息和节点的增加删除等,开发者无需关注变化过程,只需指定起点和终点的状态。animateTo还提供播放状态的回调接口,是对属性动画的增强与封装。 + +闪屏页面的动画效果是Logo图标的渐出和放大,动画结束后跳转到食物分类列表页面。接下来,我们就使用animateTo来实现启动页动画的闪屏效果。 + +1. 动画效果自动播放。闪屏动画的预期效果是,进入Logo页面后,animateTo动画效果自动开始播放,可以借助于组件显隐事件的回调接口来实现。调用Shape的onAppear方法,设置其显式动画。 + + ```ts + Shape() { + ... + } + .onAppear(() => { + animateTo() + }) + ``` + +2. 创建opacity和scale数值的成员变量,用装饰器@State修饰。表示其为有状态的数据,即改变会触发页面的刷新。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo() + }) + } + } + ``` + +3. 设置animateTo的动画曲线curve。Logo的加速曲线为先慢后快,使用贝塞尔曲线cubicBezier,cubicBezier(0.4, 0, 1, 1)。 + + 需要使用动画能力接口中的插值计算,首先要导入curves模块。 + + ```ts + import Curves from '@ohos.curves' + ``` + + @ohos.curves模块提供了线性Curve. Linear、阶梯step、三阶贝塞尔(cubicBezier)和弹簧(spring)插值曲线的初始化函数,可以根据入参创建一个插值曲线对象。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + curve: this.curve1 + }) + }) + } + } + ``` + +4. 设置动画时长为1s,延时0.1s开始播放,设置显示动效event的闭包函数,即起点状态到终点状态为透明度opacityValue和大小scaleValue从0到1,实现Logo的渐出和放大效果。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + } + } + ``` + +5. 闪屏动画播放结束后定格1s,进入FoodCategoryList页面。设置animateTo的onFinish回调接口,调用定时器Timer的setTimeout接口延时1s后,调用router.replace,显示FoodCategoryList页面。 + + ```ts + import router from '@ohos.router' + + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + onFinish: () => { + setTimeout(() => { + router.replace({ url: "pages/FoodCategoryList" }) + }, 1000); + } + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + } + } + ``` + + 整体代码如下。 + + ```ts + import Curves from '@ohos.curves' + import router from '@ohos.router' + + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + private pathCommands1: string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2: string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + onFinish: () => { + setTimeout(() => { + router.replace({ url: "pages/FoodCategoryList" }) + }, 1000); + } + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + + Text('Healthy Diet') + .fontSize(26) + .fontColor(Color.White) + .margin({ top: 300 }) + + Text('Healthy life comes from a balanced diet') + .fontSize(17) + .fontColor(Color.White) + .margin({ top: 4 }) + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![animation-feature](figures/animation-feature.gif) + +## 页面转场动画 + +食物分类列表页和食物详情页之间的共享元素转场,即点击FoodListItem/FoodGridItem后,食物缩略图会放大,随着页面跳转,到食物详情页的大图。 + +1. 设置FoodListItem和FoodGridItem的Image组件的共享元素转场方法(sharedTransition)。转场id为foodItem.id,转场动画时长为1s,延时0.1s播放,变化曲线为贝塞尔曲线Curves.cubicBezier(0.2, 0.2, 0.1, 1.0) ,需引入curves模块。 + + 共享转场时会携带当前元素的被设置的属性,所以创建Row组件,使其作为Image的父组件,设置背景颜色在Row上。 + + 在FoodListItem的Image组件上设置autoResize为false,因为image组件默认会根据最终展示的区域,去调整图源的大小,以优化图片渲染性能。在转场动画中,图片在放大的过程中会被重新加载,所以为了转场动画的流畅,autoResize设置为false。 + + ```ts + // FoodList.ets + import Curves from '@ohos.curves' + + @Component + struct FoodListItem { + private foodItem: FoodData + build() { + Navigator({ target: 'pages/FoodDetail' }) { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .autoResize(false) + .height(40) + .width(40) + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + } + + .margin({ right: 16 }) + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + Text(this.foodItem.calories + ' kcal') + .fontSize(14) + } + .height(64) + } + .params({ foodData: this.foodItem }) + .margin({ right: 24, left:32 }) + } + } + + @Component + struct FoodGridItem { + private foodItem: FoodData + build() { + Column() { + Row() { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .autoResize(false) + .height(152) + .width('100%') + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + } + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + .padding({ left: 8 }) + Text(this.foodItem.calories + 'kcal') + .fontSize(14) + .margin({ right: 6 }) + } + .height(32) + .width('100%') + .backgroundColor('#FFe5e5e5') + } + .height(184) + .width('100%') + .onClick(() => { + router.push({ url: 'pages/FoodDetail', params: { foodId: this.foodItem } }) + }) + } + } + + + ``` + +2. 设置FoodDetail页面的FoodImageDisplay的Image组件的共享元素转场方法(sharedTransition)。设置方法同上。 + + ```ts + import Curves from '@ohos.curves' + + @Component + struct FoodImageDisplay { + private foodItem: FoodData + build() { + Stack({ alignContent: Alignment.BottomStart }) { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + Text(this.foodItem.name) + .fontSize(26) + .fontWeight(500) + .margin({ left: 26, bottom: 17.4 }) + } + .height(357) + } + } + ``` + + ![animation-feature1](figures/animation-feature1.gif) + + 通过对绘制组件和动画的学习,我们已完成了启动Logo的绘制、启动页动画和页面间的转场动画,声明式UI框架提供了丰富的动效接口,合理地应用和组合可以让应用更具有设计感。 + + diff --git a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md b/zh-cn/application-dev/ui/ui-ts-basic-components-button.md deleted file mode 100644 index 06ff221c14b45531dc919dca123e6d1ac28f5b43..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md +++ /dev/null @@ -1,193 +0,0 @@ -# Button - - -Button是按钮组件,通常用于响应用户的点击操作,如提交表单,其类型包括胶囊按钮、圆形按钮、普通按钮。具体用法请参考[Button](../reference/arkui-ts/ts-basic-components-button.md)。 - - -## 创建按钮 - -Button通过调用接口来创建,接口调用有以下两种形式: - -- 创建包含子组件的按钮 - - `Button(options?: {type?: ButtonType, stateEffect?: boolean})`,该接口用于创建包含子组件的按钮,其中type用于设置Button类型,stateEffect属性设置Button是否开启点击效果。 - - ``` - Button({ type: ButtonType.Normal, stateEffect: true }) { - Row() { - Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 }) - Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 }) - }.alignItems(VerticalAlign.Center) - }.borderRadius(8).backgroundColor(0x317aff).width(90) - ``` - - - ![zh-cn_image_0000001260555857](figures/zh-cn_image_0000001260555857.png) - -- 创建不包含子组件的按钮 - - `Button(label?: string, options?: { type?: ButtonType, stateEffect?: boolean })`,该接口用于创建不包含子组件的按钮,其中label确定所创建的Button是否包含子组件。 - - ``` - Button('Ok', { type: ButtonType.Normal, stateEffect: true }) - .borderRadius(8) - .backgroundColor(0x317aff) - .width(90) - ``` - - - ![zh-cn_image_0000001215796030](figures/zh-cn_image_0000001215796030.png) - - -## 设置按钮类型 - -Button有三种可选类型,分别为Capsule(胶囊类型)、Circle(圆形按钮)和Normal(普通按钮),通过type进行设置。 - -- 胶囊按钮(默认类型) - - ```ts - Button('Disable', { type: ButtonType.Capsule, stateEffect: false }) - .backgroundColor(0x317aff) - .width(90) - ``` - - ![zh-cn_image_0000001215645452](figures/zh-cn_image_0000001215645452.png) - -- 圆形按钮 - - ```ts - Button('Circle', { type: ButtonType.Circle, stateEffect: false }) - .backgroundColor(0x317aff) - .width(90) - .height(90) - ``` - - ![zh-cn_image_0000001215965420](figures/zh-cn_image_0000001215965420.png) - - -## 自定义样式 - -- 设置边框弧度 - 一般使用通用属性来自定义按钮样式。例如通过borderRadius属性设置按钮的边框弧度。 - - - ```ts - Button('circle border', { type: ButtonType.Normal }) - .borderRadius(20) - ``` - - ![zh-cn_image_0000001190463780](figures/zh-cn_image_0000001190463780.png) - -- 设置文本样式 - 通过添加文本样式设置按钮文本的展示样式。 - - - ```ts - Button('font style', { type: ButtonType.Normal }) - .fontSize(20) - .fontColor(Color.Red) - .fontWeight(800) - ``` - - ![zh-cn_image_0000001189744672](figures/zh-cn_image_0000001189744672.png) - -- 设置背景颜色 - 添加backgroundColor属性设置按钮的背景颜色。 - - - ```ts - Button('background color').backgroundColor(0xF55A42) - ``` - - ![zh-cn_image_0000001235146483](figures/zh-cn_image_0000001235146483.png) - -- 用作功能型按钮 - 为删除操作创建一个按钮。 - - - ```ts - Button({ type: ButtonType.Circle, stateEffect: true }) { - Image($r('app.media.ic_public_delete_filled')).width(30).height(30) - }.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42) - ``` - - ![zh-cn_image_0000001260373911](figures/zh-cn_image_0000001260373911.png) - - -## 添加事件 - -Button组件通常用于触发某些操作,可以在绑定onClick事件来响应点击操作后的自定义行为。 - - -```ts -Button('Ok', { type: ButtonType.Normal, stateEffect: true }) - .onClick(()=>{ - console.info('Button onClick') - }) -``` - - -## 场景示例 - -- 用于启动操作 - - 可以将按钮用于启动操作的任何用户界面元素。按钮会根据用户的操作触发相应的事件。如,在List容器里边通过点击按钮进行页面跳转: - - ```ts - // xxx.ets - import router from '@ohos.router' - - @Entry - @Component - struct ButtonCase1 { - build() { - List({ space: 4 }) { - ListItem() { - Button("First").onClick(() => { - router.push({ url: 'xxx' }) - }) - } - - ListItem() { - Button("Second").onClick(() => { - router.push({ url: 'yyy' }) - }) - } - - ListItem() { - Button("Third").onClick(() => { - router.push({ url: 'zzz' }) - }) - } - } - .listDirection(Axis.Vertical) - .backgroundColor(0xDCDCDC).padding(20) - } - } - ``` - - -​ ![zh-cn_image_0000001235626467](figures/zh-cn_image_0000001235626467.png) - - -- 用于表单的提交 - - 在用户登录/注册页面,用户的登录或注册的提交操作会用按钮。 - - ```ts - // xxx.ets - @Entry - @Component - struct ButtonCase2 { - build() { - Column() { - TextInput({ placeholder: 'input your username' }).margin({ top: 20 }) - TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 }) - Button('Register').width(300).margin({ top: 20 }) - }.padding(20) - } - } - ``` - - - ![zh-cn_image_0000001190466492](figures/zh-cn_image_0000001190466492.png) diff --git a/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md b/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md index 1f8e88029e8a192fbed74060f3c72d1e21d2357b..8df2f7bd9c6d81a5fe9778a3cfeca9185e19f19c 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md +++ b/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md @@ -1,16 +1,16 @@ # 构建食物分类Grid布局 - - 健康饮食应用在主页提供给用户两种食物显示方式:列表显示和网格显示。开发者将实现通过页签切换不同食物分类的网格布局。 1. 将Category枚举类型引入FoodCategoryList页面。 + ```ts import { Category, FoodData } from '../model/FoodData' ``` 2. 创建FoodCategoryList和FoodCategory组件,其中FoodCategoryList作为新的页面入口组件,在入口组件调用initializeOnStartup方法。 + ```ts @Component struct FoodList { @@ -19,7 +19,7 @@ ...... } } - + @Component struct FoodCategory { private foodItems: FoodData[] @@ -27,7 +27,7 @@ ...... } } - + @Entry @Component struct FoodCategoryList { @@ -39,13 +39,14 @@ ``` 3. 在FoodCategoryList组件内创建showList成员变量,用于控制List布局和Grid布局的渲染切换。需要用到条件渲染语句if...else...。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() private showList: boolean = false - + build() { Stack() { if (this.showList) { @@ -59,13 +60,14 @@ ``` 4. 在页面右上角创建切换List/Grid布局的图标。设置Stack对齐方式为顶部尾部对齐TopEnd,创建Image组件,设置其点击事件,即showList取反。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() private showList: boolean = false - + build() { Stack({ alignContent: Alignment.TopEnd }) { if (this.showList) { @@ -85,14 +87,15 @@ } ``` -5. 添加\@State装饰器。点击右上角的switch标签后,页面没有任何变化,这是因为showList不是有状态数据,它的改变不会触发页面的刷新。需要为其添加\@State装饰器,使其成为状态数据,它的改变会引起其所在组件的重新渲染。 +5. 添加@State装饰器。点击右上角的switch标签后,页面没有任何变化,这是因为showList不是有状态数据,它的改变不会触发页面的刷新。需要为其添加\@State装饰器,使其成为状态数据,它的改变会引起其所在组件的重新渲染。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() @State private showList: boolean = false - + build() { Stack({ alignContent: Alignment.TopEnd }) { if (this.showList) { @@ -110,7 +113,7 @@ }.height('100%') } } - + ``` 点击切换图标,FoodList组件出现,再次点击,FoodList组件消失。 @@ -118,6 +121,7 @@ ![zh-cn_image_0000001170411978](figures/zh-cn_image_0000001170411978.gif) 6. 创建显示所有食物的页签(All)。在FoodCategory组件内创建Tabs组件和其子组件TabContent,设置tabBar为All。设置TabBars的宽度为280,布局模式为Scrollable,即超过总长度后可以滑动。Tabs是一种可以通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图TabContent。 + ```ts @Component struct FoodCategory { @@ -137,13 +141,14 @@ ![zh-cn_image_0000001204538065](figures/zh-cn_image_0000001204538065.png) 7. 创建FoodGrid组件,作为TabContent的子组件。 + ```ts @Component struct FoodGrid { private foodItems: FoodData[] build() {} } - + @Component struct FoodCategory { private foodItems: FoodData[] @@ -162,6 +167,7 @@ ``` 8. 实现2 \* 6的网格布局(一共12个食物数据资源)。创建Grid组件,设置列数columnsTemplate('1fr 1fr'),行数rowsTemplate('1fr 1fr 1fr 1fr 1fr 1fr'),行间距和列间距rowsGap和columnsGap为8。创建Scroll组件,使其可以滑动。 + ```ts @Component struct FoodGrid { @@ -185,6 +191,7 @@ ``` 9. 创建FoodGridItem组件,展示食物图片、名称和卡路里,实现其UI布局,为GridItem的子组件。每个FoodGridItem高度为184,行间距为8,设置Grid总高度为(184 + 8) \* 6 - 8 = 1144。 + ```ts @Component struct FoodGridItem { @@ -196,7 +203,7 @@ .objectFit(ImageFit.Contain) .height(152) .width('100%') - }.backgroundColor('#FFf1f3f5') + } Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text(this.foodItem.name) .fontSize(14) @@ -214,7 +221,7 @@ .width('100%') } } - + @Component struct FoodGrid { private foodItems: FoodData[] @@ -239,123 +246,126 @@ } ``` - ![zh-cn_image_0000001170167520](figures/zh-cn_image_0000001170167520.gif) + ![zh-cn_image_0000001170167520](figures/zh-cn_image_0000001170167520.png) 10. 创建展示蔬菜(Category.Vegetable)、水果(Category.Fruit)、坚果(Category.Nut)、海鲜(Category.SeaFood)和甜品(Category.Dessert)分类的页签。 - ```ts - @Component - struct FoodCategory { - private foodItems: FoodData[] - build() { - Stack() { - Tabs() { - TabContent() { - FoodGrid({ foodItems: this.foodItems }) - }.tabBar('All') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Vegetable)) }) - }.tabBar('Vegetable') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Fruit)) }) - }.tabBar('Fruit') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Nut)) }) - }.tabBar('Nut') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Seafood)) }) - }.tabBar('Seafood') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Dessert)) }) - }.tabBar('Dessert') + + ```ts + @Component + struct FoodCategory { + private foodItems: FoodData[] + + build() { + Stack() { + Tabs() { + TabContent() { + FoodGrid({ foodItems: this.foodItems }) + }.tabBar('All') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Vegetable)) }) + }.tabBar('Vegetable') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Fruit)) }) + }.tabBar('Fruit') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Nut)) }) + }.tabBar('Nut') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Seafood)) }) + }.tabBar('Seafood') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Dessert)) }) + }.tabBar('Dessert') + } + .barWidth(280) + .barMode(BarMode.Scrollable) } - .barWidth(280) - .barMode(BarMode.Scrollable) } } - } - ``` + ``` 11. 设置不同食物分类的Grid的行数和高度。因为不同分类的食物数量不同,所以不能用'1fr 1fr 1fr 1fr 1fr 1fr '常量来统一设置成6行。 创建gridRowTemplate和HeightValue成员变量,通过成员变量设置Grid行数和高度。 - ```ts - @Component - struct FoodGrid { - private foodItems: FoodData[] - private gridRowTemplate : string = '' - private heightValue: number - build() { - Scroll() { - Grid() { - ForEach(this.foodItems, (item: FoodData) => { - GridItem() { - FoodGridItem({foodItem: item}) - } - }, (item: FoodData) => item.id.toString()) - } - .rowsTemplate(this.gridRowTemplate) - .columnsTemplate('1fr 1fr') - .columnsGap(8) - .rowsGap(8) - .height(this.heightValue) - } - .scrollBar(BarState.Off) - .padding({left: 16, right: 16}) - } - } - ``` - - 调用aboutToAppear接口计算行数(gridRowTemplate )和高度(heightValue)。 - - ```ts - aboutToAppear() { - var rows = Math.round(this.foodItems.length / 2); - this.gridRowTemplate = '1fr '.repeat(rows); - this.heightValue = rows * 192 - 8; - } - ``` - - 自定义组件提供了两个生命周期的回调接口aboutToAppear和aboutToDisappear。aboutToAppear的执行时机在创建自定义组件后,执行自定义组件build方法之前。aboutToDisappear在自定义组件销毁之前的时机执行。 + ```ts + @Component + struct FoodGrid { + private foodItems: FoodData[] + private gridRowTemplate: string = '' + private heightValue: number + + build() { + Scroll() { + Grid() { + ForEach(this.foodItems, (item: FoodData) => { + GridItem() { + FoodGridItem({ foodItem: item }) + } + }, (item: FoodData) => item.id.toString()) + } + .rowsTemplate(this.gridRowTemplate) + .columnsTemplate('1fr 1fr') + .columnsGap(8) + .rowsGap(8) + .height(this.heightValue) + } + .scrollBar(BarState.Off) + .padding({ left: 16, right: 16 }) + } + } + ``` - ![zh-cn_image_0000001215113569](figures/zh-cn_image_0000001215113569.png) + 调用aboutToAppear接口计算行数(gridRowTemplate )和高度(heightValue)。 - ```ts - @Component - struct FoodGrid { - private foodItems: FoodData[] - private gridRowTemplate : string = '' - private heightValue: number - - aboutToAppear() { - var rows = Math.round(this.foodItems.length / 2); - this.gridRowTemplate = '1fr '.repeat(rows); - this.heightValue = rows * 192 - 8; - } - - build() { - Scroll() { - Grid() { - ForEach(this.foodItems, (item: FoodData) => { - GridItem() { - FoodGridItem({foodItem: item}) - } - }, (item: FoodData) => item.id.toString()) - } - .rowsTemplate(this.gridRowTemplate) - .columnsTemplate('1fr 1fr') - .columnsGap(8) - .rowsGap(8) - .height(this.heightValue) - } - .scrollBar(BarState.Off) - .padding({left: 16, right: 16}) - } - } - ``` + ```ts + aboutToAppear() { + var rows = Math.round(this.foodItems.length / 2); + this.gridRowTemplate = '1fr '.repeat(rows); + this.heightValue = rows * 192 - 8; + } + ``` + + 自定义组件提供了两个生命周期的回调接口aboutToAppear和aboutToDisappear。aboutToAppear的执行时机在创建自定义组件后,执行自定义组件build方法之前。aboutToDisappear在自定义组件销毁之前的时机执行。 + + ![zh-cn_image_0000001215113569](figures/zh-cn_image_0000001215113569.png) + + ```ts + @Component + struct FoodGrid { + private foodItems: FoodData[] + private gridRowTemplate: string = '' + private heightValue: number + + aboutToAppear() { + var rows = Math.round(this.foodItems.length / 2); + this.gridRowTemplate = '1fr '.repeat(rows); + this.heightValue = rows * 192 - 8; + } + + build() { + Scroll() { + Grid() { + ForEach(this.foodItems, (item: FoodData) => { + GridItem() { + FoodGridItem({ foodItem: item }) + } + }, (item: FoodData) => item.id.toString()) + } + .rowsTemplate(this.gridRowTemplate) + .columnsTemplate('1fr 1fr') + .columnsGap(8) + .rowsGap(8) + .height(this.heightValue) + } + .scrollBar(BarState.Off) + .padding({ left: 16, right: 16 }) + } + } + ``` - ![zh-cn_image_0000001170008198](figures/zh-cn_image_0000001170008198.gif) + ![zh-cn_image_0000001170008198](figures/zh-cn_image_0000001170008198.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md b/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md index bb5ab8da2f5078e85109101f3f0a07257e609f40..5201e0e720b83083b0ceaeaac73ca95d15ed9290 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md +++ b/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md @@ -1,23 +1,12 @@ # 构建食物列表List布局 - - 使用List组件和ForEach循环渲染,构建食物列表布局。 -1. 在pages目录新建页面FoodCategoryList.ets,将index.ets改名为FoodDetail.ets,并将其添加到config.json文件下的pages标签,位于第一序位的页面为首页。 - ```json - "js": [ - { - "pages": [ - "pages/FoodCategoryList", - "pages/FoodDetail" - ], - ] - ``` - +1. 在pages目录新建页面FoodCategoryList.ets,将index.ets改名为FoodDetail.ets。 + 2. 新建FoodList组件作为页面入口组件,FoodListItem为其子组件。List组件是列表组件,适用于重复同类数据的展示,其子组件为ListItem,适用于展示列表中的单元。 - ``` + ```ts @Component struct FoodListItem { build() {} @@ -43,7 +32,7 @@ ``` 4. FoodList和FoodListItem组件数值传递。在FoodList组件内创建类型为FoodData[]成员变量foodItems,调用initializeOnStartup方法为其赋值。在FoodListItem组件内创建类型为FoodData的成员变量foodItem。将父组件foodItems数组的第一个元素的foodItems[0]作为参数传递给FoodListItem。 - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' @@ -68,20 +57,64 @@ ``` 5. 声明子组件FoodListItem 的UI布局。创建Flex组件,包含食物图片缩略图,食物名称,和食物对应的卡路里。 - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' + @Component + struct FoodListItem { + private foodItem: FoodData + build() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .height(40) + .width(40) + .margin({ right: 16 }) + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + Text(this.foodItem.calories + ' kcal') + .fontSize(14) + } + .height(64) + .margin({ right: 24, left:32 }) + } + } + + @Entry + @Component + struct FoodList { + private foodItems: FoodData[] = initializeOnStartup() + build() { + List() { + ListItem() { + FoodListItem({ foodItem: this.foodItems[0] }) + } + } + } + } + ``` + + + ![zh-cn_image_0000001204776353](figures/zh-cn_image_0000001204776353.png) + +6. 创建两个FoodListItem。在List组件创建两个FoodListItem,分别给FoodListItem传递foodItems数组的第一个元素this.foodItems[0]和第二个元素foodItem: this.foodItems[1]。 + + ```ts + import { FoodData } from '../model/FoodData' + import { initializeOnStartup } from '../model/FoodDataModels' + @Component struct FoodListItem { private foodItem: FoodData + build() { Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Image(this.foodItem.image) .objectFit(ImageFit.Contain) .height(40) .width(40) - .backgroundColor('#FFf1f3f5') .margin({ right: 16 }) Text(this.foodItem.name) .fontSize(14) @@ -90,62 +123,21 @@ .fontSize(14) } .height(64) - .margin({ right: 24, left:32 }) + .margin({ right: 24, left: 32 }) } } - - @Entry - @Component - struct FoodList { - private foodItems: FoodData[] = initializeOnStartup() - build() { - List() { - ListItem() { - FoodListItem({ foodItem: this.foodItems[0] }) - } - } - } - } - ``` - - ![zh-cn_image_0000001204776353](figures/zh-cn_image_0000001204776353.png) - -6. 创建两个FoodListItem。在List组件创建两个FoodListItem,分别给FoodListItem传递foodItems数组的第一个元素this.foodItems[0]和第二个元素foodItem: this.foodItems[1]。 - ``` - import { FoodData } from '../model/FoodData' - import { initializeOnStartup } from '../model/FoodDataModels' - - @Component - struct FoodListItem { - private foodItem: FoodData - build() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - Image(this.foodItem.image) - .objectFit(ImageFit.Contain) - .height(40) - .width(40) - .backgroundColor('#FFf1f3f5') - .margin({ right: 16 }) - Text(this.foodItem.name) - .fontSize(14) - .flexGrow(1) - Text(this.foodItem.calories + ' kcal') - .fontSize(14) - } - .height(64) - .margin({ right: 24, left:32 }) - } - } - + @Entry @Component struct FoodList { private foodItems: FoodData[] = initializeOnStartup() + build() { List() { ListItem() { FoodListItem({ foodItem: this.foodItems[0] }) } + ListItem() { FoodListItem({ foodItem: this.foodItems[1] }) } @@ -153,36 +145,16 @@ } } ``` + + + ![zh-cn_image1_0000001204776353](figures/zh-cn_image1_0000001204776353.png) + +7. 单独创建每一个FoodListItem肯定是不合理的,这就需要引入[ForEach循环渲染](../quick-start/arkts-rendering-control.md#循环渲染)。 - ![zh-cn_image_0000001204537865](figures/zh-cn_image_0000001204537865.png) - -7. 单独创建每一个FoodListItem肯定是不合理的。这就需要引入ForEach循环渲染,ForEach语法如下。 - ``` - ForEach( - arr: any[], // Array to be iterated - itemGenerator: (item: any) => void, // child component generator - keyGenerator?: (item: any) => string // (optional) Unique key generator, which is recommended. - ) - ``` - - ForEach组有三个参数,第一个参数是需要被遍历的数组,第二个参数为生成子组件的lambda函数,第三个参数是键值生成器。出于性能原因,即使第三个参数是可选的,强烈建议开发者提供。keyGenerator使开发框架能够更好地识别数组更改,而不必因为item的更改重建全部节点。 - - 遍历foodItems数组循环创建ListItem组件,foodItems中每一个item都作为参数传递给FoodListItem组件。 - - ``` - ForEach(this.foodItems, item => { - ListItem() { - FoodListItem({ foodItem: item }) - } - }, item => item.id.toString()) - ``` - - 整体的代码如下。 - - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' - + @Component struct FoodListItem { private foodItem: FoodData @@ -191,8 +163,7 @@ Image(this.foodItem.image) .objectFit(ImageFit.Contain) .height(40) - .width(40) - .backgroundColor('#FFf1f3f5') + .width(40) .margin({ right: 16 }) Text(this.foodItem.name) .fontSize(14) @@ -204,7 +175,7 @@ .margin({ right: 24, left:32 }) } } - + @Entry @Component struct FoodList { @@ -220,22 +191,25 @@ } } ``` - + 8. 添加FoodList标题。 + ``` @Entry @Component struct FoodList { private foodItems: FoodData[] = initializeOnStartup() + build() { Column() { - Flex({justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center}) { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text('Food List') .fontSize(20) - .margin({ left:20 }) + .margin({ left: 20 }) } .height('7%') .backgroundColor('#FFf1f3f5') + List() { ForEach(this.foodItems, item => { ListItem() { @@ -249,4 +223,4 @@ } ``` - ![zh-cn_image_0000001169678922](figures/zh-cn_image_0000001169678922.png) + ![zh-cn_image_0000001169678922](figures/zh-cn_image_0000001169678922.png) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-building-data-model.md b/zh-cn/application-dev/ui/ui-ts-building-data-model.md index b0627fe491d6207825bf775dcc9a95d1c50c9d12..4d516a2b3fa81a482ebaf5337efd7c080871bd07 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-data-model.md +++ b/zh-cn/application-dev/ui/ui-ts-building-data-model.md @@ -13,7 +13,7 @@ 2. 定义食物数据的存储模型FoodData和枚举变量Category,FoodData类包含食物id、名称(name)、分类(category)、图片(image)、热量(calories)、蛋白质(protein)、脂肪(fat)、碳水(carbohydrates)和维生素C(vitaminC)属性。 ArkTS语言是在ts语言的基础上的扩展,同样支持ts语法。 - ``` + ```ts enum Category { Fruit, Vegetable, @@ -52,7 +52,7 @@ 4. 创建食物资源数据。在model文件夹下创建FoodDataModels.ets,在该页面中声明食物成分数组FoodComposition。以下示例创建了两个食物数据。 - ``` + ```ts const FoodComposition: any[] = [ { 'name': 'Tomato', 'image': $r('app.media.Tomato'), 'category': Category.Vegetable, 'calories': 17, 'protein': 0.9, 'fat': 0.2, 'carbohydrates': 3.9, 'vitaminC': 17.8 }, { 'name': 'Walnut', 'image': $r('app.media.Walnut'), 'category': Category.Nut, 'calories': 654 , 'protein': 15, 'fat': 65, 'carbohydrates': 14, 'vitaminC': 1.3 } @@ -62,7 +62,7 @@ 实际开发中,开发者可以自定义更多的数据资源,当食物资源很多时,建议使用数据懒加载LazyForEach。 5. 创建initializeOnStartUp方法来初始化FoodData的数组。在FoodDataModels.ets中使用了定义在FoodData.ets的FoodData和Category,所以要将FoodData.ets的FoodData类export,在FoodDataModels.ets内import FoodData和Category。 - ``` + ```ts // FoodData.ets export enum Category { ...... diff --git a/zh-cn/application-dev/ui/ui-ts-components-intro.md b/zh-cn/application-dev/ui/ui-ts-components-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..5af40fbdf7ee2567a2d761431cea84c69eb31c98 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-components-intro.md @@ -0,0 +1,32 @@ +# 常用组件说明 + +组件是构建页面的核心,每个组件通过对数据和方法的简单封装,实现独立的可视、可交互功能单元。组件之间相互独立,随取随用,也可以在需求相同的地方重复使用。 + +声明式开发范式目前可供选择的组件如下表所示。 + +| 组件类型 | 主要组件 | +| ---------------------------- | ---------------------------------------------------------- | +| [基础组件](../reference/arkui-ts/ts-basic-components-blank.md) | Blank、Button、Checkbox、CheckboxGroup、DataPanel、DatePicker、Divider、Gauge、Image、ImageAnimator、LoadingProgress、Marquee、Navigation、PatternLock、PluginComponent、Progress、QRCode、Radio、Rating、RemoteWindow、RichText、ScrollBar、Search、Select、Slider、Span、Stepper、StepperItem、Text、TextArea、TextClock、TextInput、TextPicker、TextTimer、TimePicker、Toggle、Web、XComponent | +| [容器组件](../reference/arkui-ts/ts-container-ability-component.md) | AbilityComponent、AlphabetIndexer、Badge、Column、ColumnSplit、Counter、Flex、FlowItem、GridContainer、GridCol、GridRow、Grid、GridItem、List、ListItem、ListItemGroup、Navigator、Panel、Refresh、RelativeContainer、Row、RowSplit、Scroll、SideBarContainer、Stack、Swiper、Tabs、TabContent、WaterFlow | +| [媒体组件](../reference/arkui-ts/ts-media-components-video.md) | Video | +| [绘制组件](../reference/arkui-ts/ts-drawing-components-circle.md) | Circle、Ellipse、Line、Polyline、Polygon、Path、Rect、Shape | +| [画布组件](../reference/arkui-ts/ts-components-canvas-canvas.md) | Canvas | + + +## 相关实例 + +- [`Canvas`:画布组件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Canvas) + +- [`Xcomponent`:XComponent(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/XComponent) + +- [`Clock`:简单时钟(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) + +- [`PatternLock`:图案密码锁组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/PatternLock) + +- [`Search`:Search组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Search) + +- [`QRCode`:二维码(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/QRCode) + +- [基础组件Slider的使用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderApplicationEts) + +- [`Gallery`:组件集合(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) diff --git a/zh-cn/application-dev/ui/ui-ts-components.md b/zh-cn/application-dev/ui/ui-ts-components.md deleted file mode 100644 index 45d22d02d3255dddcd90760c911595a942c2ee17..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-components.md +++ /dev/null @@ -1,78 +0,0 @@ -# 初识Component - -在自定义组件之前,需要先了解什么是[组件和装饰器](#组件和装饰器),并进行初始化组件。然后通过[修改组件属性和构造参数](#修改组件属性和构造参数),实现一个自定义组件。 - - -## 组件和装饰器 - -在声明式UI中,所有的页面都是由组件构成。组件的数据结构为struct,装饰器[@Component](../ui/ts-component-based-component.md)是组件化的标志。用@Component修饰的struct表示这个结构体有了组件化的能力。 - -自定义组件的声明方式为: - -```ts -@Component -struct MyComponent {} -``` - -在IDE创建工程模板中,MyComponent就是一个可以居中显示文字的自定义组件。开发者可以在Component的build方法里描述自己的UI结构,但需要遵循Builder的接口约束。 - -```ts -interface Builder { - build: () => void -} -``` - -[@Entry](../ui/ts-component-based-entry.md)修饰的Component表示该Component是页面的总入口,也可以理解为页面的根节点。值得注意的是,一个页面有且仅能有一个@Entry,只有被@Entry修饰的组件或者其子组件,才会在页面上显示。 - -@Component和@Entry都是基础且十分重要的装饰器。简单地理解,装饰器就是某一种修饰,给被装饰的对象赋予某一种能力,比如@Entry就是页面入口的能力,@Component就是组件化能力。 - -在了解了组件和装饰器这两个重要概念后,接下来可以开始开发健康饮食应用。 - - -## 修改组件属性和构造参数 - -开发者创建系统组件时,会显示其默认样式。开发者可以通过更改组件的属性样式来改变组件的视图显示。 - -1. 修改Text组件的fontSize属性来更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。fontWeight属性支持三种设置方式: - 1. number类型的取值范围为100到900,取值间隔为100,默认为400,取值越大,字体越粗。 - 2. FontWeight为内置枚举类型,取值支持FontWeight.Lighter、FontWeight.Normal、FontWeight.Regular、FontWeight.Medium、FontWeight.Bold、FontWeight.Bolder。FontWeight.Normal即为400数值的字体粗细。 - 3. string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。设置其他字符串则为无效,保持默认字体粗细显示。 - - 属性方法要紧随组件,通过“.”运算符连接,也可以通过链式调用的方式配置组件的多个属性。 - - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(26) - .fontWeight(500) - } - .width('100%') - .height('100%') - } - } - ``` - - ![zh-cn_image_0000001168728272](figures/zh-cn_image_0000001168728272.png) - -2. 修改Text组件的显示内容“Hello World”为“Tomato”,通过修改Text组件的构造参数来实现。 - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Tomato') - .fontSize(26) - .fontWeight(500) - } - .width('100%') - .height('100%') - } - } - ``` - - ![zh-cn_image_0000001168888224](figures/zh-cn_image_0000001168888224.png) diff --git a/zh-cn/application-dev/ui/ui-ts-creating-project.md b/zh-cn/application-dev/ui/ui-ts-creating-project.md deleted file mode 100644 index e35ca9fa9b76d6dd69cbdc26864d649971265693..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-creating-project.md +++ /dev/null @@ -1,65 +0,0 @@ -# 创建声明式UI工程 - - - -创建工程之前,首先需要安装DevEco Studio。 - - -1. 打开DevEco Studio,点击Create Project。如果已有一个工程,则点击File > New > New project。 - - ![zh-cn_image_0000001168956332](figures/zh-cn_image_0000001168956332.png) - -2. - 进入选择Ability Template界面,选择Empty Ability。 - - ![zh-cn_image_0000001168059158](figures/zh-cn_image_0000001168059158.png) - -3. 进入配置工程界面,将工程名字改为HealthyDiet,Project Type选择Application,Compile API选择8,UI Syntax选择eTS。DevEco Studio会默认将工程保存在C盘,如果要更改工程保存位置,点击Save Location的文件夹图标,自行指定工程创建位置。配置完成后点击Finish。 - - - ![zh-cn_image_0000001167746622](figures/zh-cn_image_0000001167746622.png) - -4. 工程创建完成后,打开app.ets。 - app.ets提供了应用生命周期的接口:onCreate和onDestroy,分别在应用创建之初和应用被销毁时调用。在app.ets里可以声明全局变量,并且声明的数据和方法是整个应用共享的。 - - ``` - export default { - onCreate() { - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } - ``` - -5. 在工程导航栏里,打开index.ets。该页面展示了当前的UI描述,声明式UI框架会自动生成一个组件化的struct,这个struct遵循Builder接口声明,在build方法里面声明当前的布局和组件。 - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - } - .width('100%') - .height('100%') - } - } - ``` - -6. 点击右侧的Previewer按钮,打开预览窗口。可以看到预览窗口中“Hello World”居中加粗显示。 - 如果没有Previewer按钮,点击settings > SDK Manager > OpenHarmony SDK> Tools 查看是否安装了Previewer。 - - ![zh-cn_image_0000001214595111](figures/zh-cn_image_0000001214595111.png) - -7. 应用安装到设备上运行应用。 - - 将设备连接电脑,等IDE识别到物理设备后,点击Run 'entry'按钮。 - ![zh-cn_image_0000001148858818](figures/zh-cn_image_0000001148858818.png) - - 在安装之前,需要配置应用签名。安装成功后,点击屏幕上的Run图标打开应用,可以看到居中加粗显示的“Hello World”。 - - ![zh-cn_image_0000001158896538](figures/zh-cn_image_0000001158896538.png) diff --git a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md index 18152fe84e1c3ff337bd9db0b41ce9c3359adcfa..ca4fe0bd1e5f2f04a8e2aba9d881f0a37f3ac969 100644 --- a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md +++ b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md @@ -2,12 +2,16 @@ 在这一小节中,我们将开始食物详情页的开发,学习如何通过容器组件Stack、Flex和基础组件Image、Text,构建用户自定义组件,完成图文并茂的食物介绍。 +在创建页面前,请先创建eTS工程,FA模型请参考[创建FA模型的eTS工程](../quick-start/start-with-ets-stage.md#创建ets工程),Stage模型请参考[创建Stage模型的eTS工程](..//quick-start/start-with-ets-fa.md#创建ets工程)。 + ## 构建Stack布局 1. 创建食物名称。 - 删掉工程模板的build方法的代码,创建Stack组件,将Text组件放进Stack组件的花括号中,使其成为Stack组件的子组件。Stack组件为堆叠组件,可以包含一个或多个子组件,其特点是后一个子组件覆盖前一个子组件。 - ``` + + 在index.ets文件中,创建Stack组件,将Text组件放进Stack组件的花括号中,使其成为Stack组件的子组件。Stack组件为堆叠组件,可以包含一个或多个子组件,其特点是后一个子组件覆盖前一个子组件。 + + ```ts @Entry @Component struct MyComponent { @@ -22,11 +26,11 @@ ``` ![zh-cn_image_0000001214128687](figures/zh-cn_image_0000001214128687.png) - + 2. 食物图片展示。 创建Image组件,指定Image组件的url,Image组件是必选构造参数组件。为了让Text组件在Image组件上方显示,所以要先声明Image组件。图片资源放在resources下的rawfile文件夹内,引用rawfile下资源时使用`$rawfile('filename')`的形式,filename为rawfile目录下的文件相对路径。当前`$rawfile`仅支持Image控件引用图片资源。 - - ``` + + ```ts @Entry @Component struct MyComponent { @@ -42,30 +46,29 @@ ``` -![zh-cn_image_0000001168410342](figures/zh-cn_image_0000001168410342.png) + ![zh-cn_image_0000001168410342](figures/zh-cn_image_0000001168410342.png) 3. 通过资源访问图片。 除指定图片路径外,也可以使用引用媒体资源符$r引用资源,需要遵循resources文件夹的资源限定词的规则。右键resources文件夹,点击New>Resource Directory,选择Resource Type为Media(图片资源)。 将Tomato.png放入media文件夹内。就可以通过`$r('app.type.name')`的形式引用应用资源,即`$r('app.media.Tomato')`。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack() { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - + ``` 4. 设置Image宽高,并且将image的objectFit属性设置为ImageFit.Contain,即保持图片长宽比的情况下,使得图片完整地显示在边界内。 如果Image填满了整个屏幕,原因如下: @@ -73,83 +76,53 @@ 2. Image的objectFit默认属性是ImageFit.Cover,即在保持长宽比的情况下放大或缩小,使其填满整个显示边界。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack() { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - + ``` - ![zh-cn_image_0000001214210217](figures/zh-cn_image_0000001214210217.png) + ![zh-cn_image_0000001214210217](figures/zh-cn_image_0000001214210217.png) 5. 设置食物图片和名称布局。设置Stack的对齐方式为底部起始端对齐,Stack默认为居中对齐。设置Stack构造参数alignContent为Alignment.BottomStart。其中Alignment和FontWeight一样,都是框架提供的内置枚举类型。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack({ alignContent: Alignment.BottomStart }) { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - - - ![zh-cn_image_0000001168728872](figures/zh-cn_image_0000001168728872.png) - -6. 通过设置Stack的背景颜色来改变食物图片的背景颜色,设置颜色有四种方式: - 1. 通过框架提供的Color内置枚举值来设置,比如backgroundColor(Color.Red),即设置背景颜色为红色。 - 2. string类型参数,支持的颜色格式有:rgb、rgba和HEX颜色码。比如backgroundColor('\#0000FF'),即设置背景颜色为蓝色,backgroundColor('rgb(255, 255, 255)'),即设置背景颜色为白色。 - 3. number类型参数,支持十六进制颜色值。比如backgroundColor(0xFF0000),即设置背景颜色为红色。 - - 4. Resource类型参数请参考[资源访问](ts-resource-access.md) 。 - - -``` -@Entry - @Component - struct MyComponent { - build() { - Stack({ alignContent: Alignment.BottomStart }) { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) - } - .backgroundColor('#FFedf2f5') - } -} -``` + ``` + ![zh-cn_image_0000001168728872](figures/zh-cn_image_0000001168728872.png) - ![zh-cn_image_0000001168888822](figures/zh-cn_image_0000001168888822.png) +6. 调整Text组件的外边距margin,使其距离左侧和底部有一定的距离。margin是简写属性,可以统一指定四个边的外边距,也可以分别指定。具体设置方式如下: -7. 调整Text组件的外边距margin,使其距离左侧和底部有一定的距离。margin是简写属性,可以统一指定四个边的外边距,也可以分别指定。具体设置方式如下: 1. 参数为Length时,即统一指定四个边的外边距,比如margin(20),即上、右、下、左四个边的外边距都是20。 2. 参数为{top?: Length, right?: Length, bottom?: Length, left?:Length},即分别指定四个边的边距,比如margin({ left: 26, bottom: 17.4 }),即左边距为26,下边距为17.4。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { @@ -161,20 +134,19 @@ .fontSize(26) .fontWeight(500) .margin({left: 26, bottom: 17.4}) - } - .backgroundColor('#FFedf2f5') + } } } -``` + ``` + ![zh-cn_image_0000001213968747](figures/zh-cn_image_0000001213968747.png) - ![zh-cn_image_0000001213968747](figures/zh-cn_image_0000001213968747.png) +7. 调整组件间的结构,语义化组件名称。创建页面入口组件为FoodDetail,在FoodDetail中创建Column,设置水平方向上居中对齐 alignItems(HorizontalAlign.Center)。MyComponent组件名改为FoodImageDisplay,为FoodDetail的子组件。 -8. 调整组件间的结构,语义化组件名称。创建页面入口组件为FoodDetail,在FoodDetail中创建Column,设置水平方向上居中对齐 alignItems(HorizontalAlign.Center)。MyComponent组件名改为FoodImageDisplay,为FoodDetail的子组件。 Column是子组件竖直排列的容器组件,本质为线性布局,所以只能设置交叉轴方向的对齐。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -185,11 +157,10 @@ .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) } - .height(357) - .backgroundColor('#FFedf2f5') + .height(357) } } - + @Entry @Component struct FoodDetail { @@ -200,9 +171,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - - + ``` ## 构建Flex布局 @@ -210,8 +179,8 @@ 1. 创建ContentTable组件,使其成为页面入口组件FoodDetail的子组件。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -223,15 +192,15 @@ .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) } - .backgroundColor('#FFedf2f5') } } - + @Component struct ContentTable { - build() {} + build() { + } } - + @Entry @Component struct FoodDetail { @@ -243,8 +212,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` 2. 创建Flex组件展示Tomato两类成分。 一类是热量Calories,包含卡路里(Calories);一类是营养成分Nutrition,包含蛋白质(Protein)、脂肪(Fat)、碳水化合物(Carbohydrates)和维生素C(VitaminC)。 @@ -253,8 +221,8 @@ 已省略FoodImageDisplay代码,只针对ContentTable进行扩展。 -``` -@Component + ```ts + @Component struct ContentTable { build() { Flex() { @@ -270,7 +238,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -282,15 +250,15 @@ .alignItems(HorizontalAlign.Center) } } -``` - - - ![zh-cn_image_0000001169759552](figures/zh-cn_image_0000001169759552.png) - + ``` + + + ![zh-cn_image_0000001169759552](figures/zh-cn_image_0000001169759552.png) + 3. 调整布局,设置各部分占比。分类名占比(layoutWeight)为1,成分名和成分含量一共占比(layoutWeight)2。成分名和成分含量位于同一个Flex中,成分名占据所有剩余空间flexGrow(1)。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -301,11 +269,10 @@ .fontSize(26) .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) - } - .backgroundColor('#FFedf2f5') + } } } - + @Component struct ContentTable { build() { @@ -327,7 +294,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -339,16 +306,15 @@ .alignItems(HorizontalAlign.Center) } } -``` - - - ![zh-cn_image_0000001215079443](figures/zh-cn_image_0000001215079443.png) - + ``` + + ![zh-cn_image_0000001215079443](figures/zh-cn_image_0000001215079443.png) + 4. 仿照热量分类创建营养成分分类。营养成分部分(Nutrition)包含:蛋白质(Protein)、脂肪(Fat)、碳水化合物(Carbohydrates)和维生素C(VitaminC)四个成分,后三个成分在表格中省略分类名,用空格代替。 设置外层Flex为竖直排列FlexDirection.Column, 在主轴方向(竖直方向)上等距排列FlexAlign.SpaceBetween,在交叉轴方向(水平轴方向)上首部对齐排列ItemAlign.Start。 -``` -@Component + ```ts + @Component struct ContentTable { build() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { @@ -427,7 +393,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -439,8 +405,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` 5. 使用自定义构造函数\@Builder简化代码。可以发现,每个成分表中的成分单元其实都是一样的UI结构。 ![zh-cn_image_0000001169599582](figures/zh-cn_image_0000001169599582.png) @@ -449,8 +414,8 @@ 在ContentTable内声明\@Builder修饰的IngredientItem方法,用于声明分类名、成分名称和成分含量UI描述。 -``` - @Component + ```ts + @Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -469,13 +434,12 @@ } } } -``` - + ``` - 在ContentTable的build方法内调用IngredientItem接口,需要用this去调用该Component作用域内的方法,以此来区分全局的方法调用。 + 在ContentTable的build方法内调用IngredientItem接口,需要用this去调用该Component作用域内的方法,以此来区分全局的方法调用。 -``` -@Component + ```ts + @Component struct ContentTable { ...... build() { @@ -490,13 +454,12 @@ .padding({ top: 30, right: 30, left: 30 }) } } -``` - + ``` - ContentTable组件整体代码如下。 + ContentTable组件整体代码如下。 -``` -@Component + ```ts + @Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -514,21 +477,20 @@ .layoutWeight(2) } } - - build() { - Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { - this.IngredientItem('Calories', 'Calories', '17kcal') - this.IngredientItem('Nutrition', 'Protein', '0.9g') - this.IngredientItem('', 'Fat', '0.2g') - this.IngredientItem('', 'Carbohydrates', '3.9g') - this.IngredientItem('', 'VitaminC', '17.8mg') - } - .height(280) - .padding({ top: 30, right: 30, left: 30 }) - } - + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { + this.IngredientItem('Calories', 'Calories', '17kcal') + this.IngredientItem('Nutrition', 'Protein', '0.9g') + this.IngredientItem('', 'Fat', '0.2g') + this.IngredientItem('', 'Carbohydrates', '3.9g') + this.IngredientItem('', 'VitaminC', '17.8mg') + } + .height(280) + .padding({ top: 30, right: 30, left: 30 }) + } } - + @Entry @Component struct FoodDetail { @@ -540,10 +502,9 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` - ![zh-cn_image_0000001215199399](figures/zh-cn_image_0000001215199399.png) + ![zh-cn_image_0000001215199399](figures/zh-cn_image_0000001215199399.png) 通过学习Stack布局和Flex布局已完成食物的图文展示和营养成分表,构建出第一个普通视图的食物详情页。在下一个章节中,将开发食物分类列表页,并完成食物分类列表页面和食物详情页面的跳转和数据传递,现在我们就进入下一个章节的学习吧。 diff --git a/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..a4fd8f633c2f4e127f0f574c979fc51755f52c0b --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md @@ -0,0 +1,225 @@ +# 自定义组件的生命周期 + +自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。 + +> **说明:** +> +> - 允许在生命周期函数中使用Promise和异步回调函数,比如网络资源获取,定时器设置等; +> +> - 不允许在生命周期函数中使用async await。 + + +## aboutToAppear + +aboutToAppear?(): void + +aboutToAppear函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。 + +## aboutToDisappear + +aboutToDisappear?(): void + +aboutToDisappear函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。 + +**示例1:** + +```ts +// xxx.ets +@Entry +@Component +struct CountDownTimerComponent { + @State countDownFrom: number = 10 + private timerId: number = -1 + + aboutToAppear(): void { + this.timerId = setInterval(() => { + if (this.countDownFrom <= 1) { + clearTimeout(this.timerId) // countDownFrom小于等于1时清除计时器 + } + this.countDownFrom -= 1 + }, 1000) // countDownFrom每1s减1 + } + + aboutToDisappear(): void { + if (this.timerId > 0) { + clearTimeout(this.timerId) + this.timerId = -1 + } + } + + build() { + Column() { + Text(`${this.countDownFrom} sec left`) + .fontSize(30) + .margin(30) + }.width('100%') + } +} +``` + +![aboutToAppear](figures/aboutToAppear.gif) + +上述示例表明,生命周期函数对于允许CountDownTimerComponent管理其计时器资源至关重要,类似的函数也包括异步从网络请求加载资源。 + +## onPageShow + +onPageShow?(): void + +页面每次显示时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 + +## onPageHide + +onPageHide?(): void + +页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 + +## onBackPress + +onBackPress?(): void + +当用户点击返回按钮时触发,仅@Entry修饰的自定义组件生效。返回true表示页面自己处理返回逻辑,不进行页面路由,返回false表示使用默认的路由返回逻辑。不设置返回值按照false处理。 + +**示例2:** + +```ts +// xxx.ets +@Entry +@Component +struct IndexComponent { + @State textColor: Color = Color.Black + + onPageShow() { + this.textColor = Color.Blue + console.info('IndexComponent onPageShow') + } + + onPageHide() { + this.textColor = Color.Transparent + console.info('IndexComponent onPageHide') + } + + onBackPress() { + this.textColor = Color.Red + console.info('IndexComponent onBackPress') + } + + build() { + Column() { + Text('Hello World') + .fontColor(this.textColor) + .fontSize(30) + .margin(30) + }.width('100%') + } +} +``` + +![lifecycle](figures/lifecycle.PNG) + +## onLayout9+ + +onLayout?(children: Array\, constraint: ConstraintSizeOptions): void + +框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------- | -------------------------------------------------------------------------------- | ---------------------- | +| children | Array\<[LayoutChild](#layoutchild9)\> | 子组件布局信息。 | +| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 父组件constraint信息。 | + +## onMeasure9+ + +onMeasure?(children: Array\, constraint: ConstraintSizeOptions): void + +框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量。 + +**参数:** + +| 参数名 | 类型 | 说明 | +| ---------- | -------------------------------------------------------------------------------- | ---------------------- | +| children | Array\<[LayoutChild](#layoutchild9)\> | 子组件布局信息。 | +| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 父组件constraint信息。 | + +## LayoutChild9+ + +子组件布局信息。 + +| 参数 | 参数类型 | 描述 | +| ---------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------- | +| name | string | 子组件名称。 | +| id | string | 子组件id。 | +| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 子组件约束尺寸。 | +| borderInfo | [LayoutBorderInfo](#layoutborderinfo9) | 子组件border信息。 | +| position | [Position](../reference/arkui-ts/ts-types.md#position) | 子组件位置坐标。 | +| measure | (childConstraint: [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions)) => void | 调用此方法对子组件的尺寸范围进行限制。 | +| layout | (LayoutInfo: [LayoutInfo](#layoutinfo9)) => void | 调用此方法对子组件的位置信息进行限制。 | + +## LayoutBorderInfo9+ + +子组件border信息。 + +| 参数 | 参数类型 | 描述 | +| ----------- | ---------------------------------------------------------- | ---------------------------------------------- | +| borderWidth | [EdgeWidths](../reference/arkui-ts/ts-types.md#edgewidths) | 边框宽度类型,用于描述组件边框不同方向的宽度。 | +| margin | [Margin](../reference/arkui-ts/ts-types.md#margin) | 外边距类型,用于描述组件不同方向的外边距。 | +| padding | [Padding](../reference/arkui-ts/ts-types.md#padding) | 内边距类型,用于描述组件不同方向的内边距。 | + +## LayoutInfo9+ + +子组件layout信息。 + +| 参数 | 参数类型 | 描述 | +| ---------- | -------------------------------------------------------------------------------- | ---------------- | +| position | [Position](../reference/arkui-ts/ts-types.md#position) | 子组件位置坐标。 | +| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 子组件约束尺寸。 | + +**示例3:** + +```ts +// xxx.ets +@Entry +@Component +struct Index { + build() { + Column() { + CustomLayout() { + ForEach([1, 2, 3], (index) => { + Text('Sub' + index) + .fontSize(30) + .borderWidth(2) + }) + } + } + } +} + + +@Component +struct CustomLayout { + @BuilderParam builder: () => {} + + onLayout(children: Array, constraint: ConstraintSizeOptions) { + let pos = 0 + children.forEach((child) => { + child.layout({ position: { x: pos, y: pos }, constraint: constraint }) + pos += 100 + }) + } + + onMeasure(children: Array, constraint: ConstraintSizeOptions) { + let size = 100 + children.forEach((child) => { + child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size }) + size += 50 + }) + } + + build() { + this.builder() + } +} +``` + +![customlayout](figures/customLayout.png) diff --git a/zh-cn/application-dev/ui/ui-ts-developing-intro.md b/zh-cn/application-dev/ui/ui-ts-developing-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..d5bfbf46859bb2fe260f18d63eedf15aa7fb768f --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-developing-intro.md @@ -0,0 +1,227 @@ +# 声明式UI开发指导 + +## 开发说明 + +声明式UI的工程结构还请参考[OpenHarmony APP工程结构介绍](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section133380945818)。其中,.ets结尾的ArkTS文件用于描述UI布局、样式、事件交互和页面逻辑,支持导入TypeScript和JavaScript文件。资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源分类与访问](../quick-start/resource-categories-and-access.md)。 + +在开发页面之前,请先[学习ArkTS语言](../quick-start/arkts-get-started.md)了解声明式UI的基本语法。 + +在开发页面时,可先根据使用场景,在[常见布局](ui-ts-layout-linear.md)中选择合适的布局。再根据页面需要实现的内容,为页面添加系统内置组件,更新组件状态。页面开发过程中请参考[自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md)了解如何添加需要的生命周期回调方法。 + +也可在页面中添加[绘图](../reference/arkui-ts/ts-drawing-components-circle.md)和[动画](../reference/arkui-ts/ts-animatorproperty.md),丰富页面的展现形态。还可以使用[路由](../reference/apis/js-apis-router.md)实现多个页面之间的跳转和数据传递。 + +另外请参考[性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md),避免低性能代码对应用的性能造成负面影响。 + +## 创建页面 + +请先根据页面预期效果选择布局结构创建页面,并在页面中添加基础的系统内置组件。下述示例采用了[弹性布局(Flex)](ui-ts-layout-flex.md),对页面中的Text组件进行横纵向居中布局显示。 + + ```ts + // xxx.ets + @Entry + @Component + struct MyComponent { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello') + } + .width('100%') + .height('100%') + } + } + ``` + +## 修改组件样式 + +创建系统内置组件时,若不设置属性方法,则会显示其默认样式。通过更改组件的属性样式或者组件支持的[通用属性](../reference/arkui-ts/ts-universal-attributes-size.md)样式,设置可以改变组件的UI显示。 + +1. 通过修改Text组件的构造参数,将Text组件的显示内容修改为“Tomato”。 + +2. 修改Text组件的fontSize属性更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。fontWeight属性支持三种设置方式: + + a. number类型的取值范围为100到900,取值间隔为100,默认为400,取值越大,字体越粗。 + + b. FontWeight为内置枚举类型,取值支持FontWeight.Lighter、FontWeight.Normal、FontWeight.Regular、FontWeight.Medium、FontWeight.Bold、FontWeight.Bolder。FontWeight.Normal即为400数值的字体粗细。 + + c. string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。设置其他字符串则为无效,保持默认字体粗细显示。 + + 属性方法要紧随组件,通过“.”操作符连接,也可以通过链式调用的方式配置组件的多个属性。 + + ```ts + // xxx.ets + @Entry + @Component + struct MyComponent { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Tomato') + .fontSize(26) + .fontWeight(500) + } + .width('100%') + .height('100%') + } + } + ``` + + ![zh-cn_image_0000001168888224](figures/zh-cn_image_0000001168888224.png) + +## 组件成员变量初始化 + +自定义组件的成员变量可以通过[本地初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)和[在构造组件时通过构造参数初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)两种方式实现,具体允许哪种方式取决于该变量所使用的装饰器: + + +**示例:** + +```ts +// xxx.ets +class ClassA { + public str: string + + constructor(str: string) { + this.str = str + } +} + +@Entry +@Component +struct Parent { + // Parent的变量parentState进行本地初始化 + @State parentState: ClassA = new ClassA('hello') + + build() { + Column() { + Row() { + CompA({ aState: new ClassA('Tomato'), aLink: $parentState }) + } + // aState在CompA中已进行初始化,因此可以缺省 + Row() { + CompA({ aLink: $parentState }) + } + }.width('100%') + } +} + +@Component +struct CompA { + // CompA中的变量aState进行本地初始化,aLink在Parent中使用时通过构造参数初始化 + @State aState: any = new ClassA('CompA') + @Link aLink: ClassA + + build() { + Row() { + Text(JSON.stringify(this.aState)).fontSize(20).margin(30) + Text(JSON.stringify(this.aLink)).fontSize(20).margin(30) + } + } +} +``` + +![component](figures/component.PNG) + +## 组件的状态更新 + +组件的状态可以通过动态修改组件成员变量的值来更新,下面以示例来进行说明。 + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct ParentComp { + @State isCountDown: boolean = true + + build() { + Column() { + Text(this.isCountDown ? 'Count Down' : 'Stopwatch').fontSize(20).margin(20) + if (this.isCountDown) { + // 图片资源放在media目录下 + Image($r("app.media.countdown")).width(120).height(120) + TimerComponent({ counter: 10, changePerSec: -1, showInColor: Color.Red }) + } else { + // 图片资源放在media目录下 + Image($r("app.media.stopwatch")).width(120).height(120) + TimerComponent({ counter: 0, changePerSec: +1, showInColor: Color.Black }) + } + Button(this.isCountDown ? 'Switch to Stopwatch' : 'Switch to Count Down') + .onClick(() => { + this.isCountDown = !this.isCountDown + }) + }.width('100%') + } +} + +// 自定义计时器/倒计时组件 +@Component +struct TimerComponent { + @State counter: number = 0 + private changePerSec: number = -1 + private showInColor: Color = Color.Black + private timerId: number = -1 + + build() { + Text(`${this.counter}sec`) + .fontColor(this.showInColor) + .fontSize(20) + .margin(20) + } + + aboutToAppear() { + this.timerId = setInterval(() => { + this.counter += this.changePerSec + }, 1000) + } + + aboutToDisappear() { + if (this.timerId > 0) { + clearTimeout(this.timerId) + this.timerId = -1 + } + } +} +``` + +![component](figures/component.gif) + +**初始创建和渲染:** + +1. 创建父组件ParentComp; + +2. 本地初始化ParentComp的状态变量isCountDown; + +3. 执行ParentComp的build函数; + +4. 创建Column组件; + 1. 创建Text组件,设置其文本展示内容,并将Text组件实例添加到Column中; + 2. 判断if条件,创建true条件下的元素; + 1. 创建Image组件,并设置其图片源地址; + 2. 使用给定的构造函数创建TimerComponent; + 1. 创建TimerComponent对象; + 2. 本地初始化成员变量初始值; + 3. 使用TimerComponent构造函数提供的参数更新成员变量的值; + 4. 执行TimerComponent的aboutToAppear函数; + 5. 执行TimerComponent的build函数,创建相应的UI描述结构; + 3. 创建Button内置组件,设置相应的内容。 + +**状态更新:** + +用户单击按钮时: + +1. ParentComp的isCountDown状态变量的值更改为false; + +2. 执行ParentComp的build函数; + +3. Column组件被重用并执行重新初始化; + +4. Column的子组件会重用内存中的对象,但会进行重新初始化; + 1. Text组件会被重用,但使用新的文本内容进行重新初始化; + 2. 判断if条件,使用false条件下的元素; + 1. 原来true条件的组件不再使用,将这些组件销毁; + 1. 销毁Image组件实例; + 2. 销毁TimerComponent组件实例,aboutToDisappear函数被调用; + 2. 创建false条件下的组件; + 1. 创建Image组件,并设置其图片源地址; + 2. 使用给定的构造函数重新创建TimerComponent; + 3. 初始化TimerComponent,并调用aboutToAppear函数和build函数。 + 3. 重用Button组件,使用新的图片源地址。 diff --git a/zh-cn/application-dev/ui/ui-ts-drawing-feature.md b/zh-cn/application-dev/ui/ui-ts-drawing-feature.md new file mode 100644 index 0000000000000000000000000000000000000000..915748a8acec87ff5a2ef16820467d3999e4d432 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-drawing-feature.md @@ -0,0 +1,404 @@ +# 绘制图形 + +绘制能力主要是通过框架提供的绘制组件来支撑,支持svg标准绘制命令。 + +本节主要学习如何使用绘制组件,绘制详情页食物成分标签(基本几何图形)和应用Logo(自定义图形)。 + +## 绘制基本几何图形 + +绘制组件封装了一些常见的基本几何图形,比如矩形Rect、圆形Circle、椭圆形Ellipse等,为开发者省去了路线计算的过程。 + +FoodDetail页面的食物成分表里,给每一项成分名称前都加上一个圆形的图标作为成分标签。 + +1. 创建Circle组件,在每一项含量成分前增加一个圆形图标作为标签。设置Circle的直径为 6vp。修改FoodDetail页面的ContentTable组件里的IngredientItem方法,在成分名称前添加Circle。 + + ```ts + // FoodDetail.ets + @Component + struct ContentTable { + private foodItem: FoodData + + @Builder IngredientItem(title:string, colorValue: string, name: string, value: string) { + Flex() { + Text(title) + .fontSize(17.4) + .fontWeight(FontWeight.Bold) + .layoutWeight(1) + Flex({ alignItems: ItemAlign.Center }) { + Circle({width: 6, height: 6}) + .margin({right: 12}) + .fill(colorValue) + Text(name) + .fontSize(17.4) + .flexGrow(1) + Text(value) + .fontSize(17.4) + } + .layoutWeight(2) + } + } + + build() { + ...... + } + } + ``` + +2. 每个成分的标签颜色不一样,所以我们在build方法中,调用IngredientItem,给每个Circle填充不一样的颜色。 + + ```ts + // FoodDetail.ets + @Component + struct ContentTable { + private foodItem: FoodData + + @Builder IngredientItem(title:string, colorValue: string, name: string, value: string) { + Flex() { + Text(title) + .fontSize(17.4) + .fontWeight(FontWeight.Bold) + .layoutWeight(1) + Flex({ alignItems: ItemAlign.Center }) { + Circle({width: 6, height: 6}) + .margin({right: 12}) + .fill(colorValue) + Text(name) + .fontSize(17.4) + .flexGrow(1) + Text(value) + .fontSize(17.4) + } + .layoutWeight(2) + } + } + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { + this.IngredientItem('Calories', '#FFf54040', 'Calories', this.foodItem.calories + 'kcal') + this.IngredientItem('Nutrition', '#FFcccccc', 'Protein', this.foodItem.protein + 'g') + this.IngredientItem(' ', '#FFf5d640', 'Fat', this.foodItem.fat + 'g') + this.IngredientItem(' ', '#FF9e9eff', 'Carbohydrates', this.foodItem.carbohydrates + 'g') + this.IngredientItem(' ', '#FF53f540', 'VitaminC', this.foodItem.vitaminC + 'mg') + } + .height(280) + .padding({ top: 30, right: 30, left: 30 }) + } + } + ``` + + ![drawing-feature](figures/drawing-feature.png) + +## 绘制自定义几何图形 + +除绘制基础几何图形,开发者还可以使用Path组件来绘制自定义的路线,下面进行绘制应用的Logo图案。 + +1. 在pages文件夹下创建新的eTS页面Logo.ets。 + + ![drawing-feature1](figures/drawing-feature1.png) + +2. Logo.ets中删掉模板代码,创建Logo Component。 + + ```ts + @Entry + @Component + struct Logo { + build() { + } + } + ``` + +3. 创建Flex组件为根节点,宽高设置为100%,设置其在主轴方向和交叉轴方向的对齐方式都为Center,创建Shape组件为Flex子组件。 + + Shape组件是所有绘制组件的父组件。如果需要组合多个绘制组件成为一个整体,需要创建Shape作为其父组件。 + + 我们要绘制的Logo的大小630px * 630px。声明式UI范式支持多种长度单位的设置,在前面的章节中,我们直接使用number作为参数,即采用了默认长度单位vp,虚拟像素单位。vp和设备分辨率以及屏幕密度有关。比如设备分辨率为1176 * 2400,屏幕基准密度(resolution)为3,vp = px / resolution,则该设备屏幕宽度是392vp。 + + 但是绘制组件采用svg标准,默认采取px为单位的,为方便统一,在这绘制Logo这一部分,统一采取px为单位。声明式UI框架同样也支持px单位,入参类型为string,设置宽度为630px,即210vp,设置方式为width('630px')或者width(210)。 + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + } + } + ``` + +4. 给页面填充渐变色。设置为线性渐变,偏移角度为180deg,三段渐变 #BDE895 -->95DE7F --> #7AB967,其区间分别为[0, 0.1], (0.1, 0.6], (0.6, 1]。 + + ```ts + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + ``` + + ![drawing-feature2](figures/drawing-feature2.png) + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature3](figures/drawing-feature3.png) + +5. 绘制第一条路线Path,设置其绘制命令。 + + ```ts + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + ``` + + Path的绘制命令采用svg标准,上述命令可分解为: + + ```ts + M162 128.7 + ``` + + 将笔触移动到(Moveto)坐标点(162, 128.7)。 + + ```ts + a222 222 0 0 1 100.8 374.4 + ``` + + 画圆弧线(elliptical arc)半径rx,ry为222,x轴旋转角度x-axis-rotation为0,角度大小large-arc-flag为0,即小弧度角,弧线方向(sweep-flag)为1,即逆时针画弧线,小写a为相对位置,即终点坐标为(162 + 100.8 = 262.8, 128.7 + 374.4 = 503.1)。 + + ```ts + H198 + ``` + + 画水平线(horizontal lineto)到198,即画(262.8, 503.1)到(198, 503.1)的水平线。 + + ```ts + a36 36 0 0 3 -36 -36 + ``` + + 画圆弧线(elliptical arc),含义同上,结束点为(198 - 36 = 162, 503.1 - 36 = 467.1)。 + + ```ts + V128.7 + ``` + + 画垂直线(vertical lineto)到128.7,即画(162, 467.1)到(162, 128.7)的垂直线。 + + ```ts + z + ``` + + 关闭路径(closepath)。 + + ![drawing-feature4](figures/drawing-feature4.png) + + 填充颜色为白色。 + + ```ts + .fill(Color.White) + ``` + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature5](figures/drawing-feature5.png) + +6. 在Shape组件内绘制第二个Path。第二条Path的背景色为渐变色,但是渐变色的填充是其整体的box,所以需要clip将其裁剪,入参为Shape,即按照Shape的形状进行裁剪。 + + ```ts + Path() + .commands('M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z') + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands('M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z')) + ``` + + Path的绘制命令比较长,可以将其作为组件的成员变量,通过this调用。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + build() { + ...... + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + ...... + } + } + ``` + + ![drawing-feature6](figures/drawing-feature6.png) + +7. 在Shape组件内绘制第二个Path。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2:string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature7](figures/drawing-feature7.png) + + 完成应用Logo的绘制。Shape组合了三个Path组件,通过svg命令绘制出一个艺术的叶子,寓意绿色健康饮食方式。 + +8. 添加应用的标题和slogan。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2:string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + + Text('Healthy Diet') + .fontSize(26) + .fontColor(Color.White) + .margin({ top:300 }) + + Text('Healthy life comes from a balanced diet') + .fontSize(17) + .fontColor(Color.White) + .margin({ top:4 }) + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature8](figures/drawing-feature8.png) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-layout-flex.md b/zh-cn/application-dev/ui/ui-ts-layout-flex.md index 16479a4c171c4459bebb61ca67e9ca9058a80c19..3d33681082d1dc1014a17a4a9dae262a7a9e359f 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-flex.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-flex.md @@ -1,351 +1,560 @@ # 弹性布局 +弹性布局(Flex布局)是自适应布局中使用最为灵活的布局。弹性布局提供一种更加有效的方式来对容器中的子组件进行排列、对齐和分配空白空间。弹性布局 -Flex组件用于创建弹性布局,开发者可以通过Flex的接口创建容器组件,进而对容器内的其他元素进行弹性布局,例如:使三个元素在容器内水平居中,垂直等间隔分散。 +- 容器: [Flex组件](../reference/arkui-ts/ts-container-flex.md)作为Flex布局的容器,用于设置布局相关属性。 +- 子组件: Flex组件内的子组件自动成为布局的子组件。 +- 主轴: 水平方向的轴线,子组件默认沿着主轴排列。主轴开始的位置称为主轴起始端,结束位置称为主轴终点端。 +- 交叉轴: 垂直方向的轴线。交叉始的位置称为主轴首部,结束位置称为交叉轴尾部。 -## 创建弹性布局 + ![](figures/flex.png) -接口的调用形式如下: +## 容器组件属性 -`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` -通过参数direction定义弹性布局的布局方向,justifyContent定义弹性布局方向上的子组件对齐方式, alignContent定义与布局方向垂直的方向上的子组件对齐方式,wrap定义内容超过一行时是否换行。 - -## 弹性布局方向 +通过Flex组件提供的Flex接口创建弹性布局。如下: -弹性布局有两个方向,子组件放置的方向是主轴,与主轴垂直的方向是交叉轴。通过direction参数设置容器主轴的方向,可选值有: +`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` -- FlexDirection.Row(默认值):主轴为水平方向,子组件从起始端沿着水平方向开始排布。 - ```ts - Flex({ direction: FlexDirection.Row }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.png) +### 弹性布局方向 +参数direction决定主轴的方向,即子组件的排列方向。可选值有: -- FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection.Row相反的方向开始排布。 +![](figures/direction.png) - ```ts - Flex({ direction: FlexDirection.RowReverse }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` +- FlexDirection.Row(默认值):主轴为水平方向,子组件从起始端沿着水平方向开始排布。 - ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.png) + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.png) + +- FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection. Row相反的方向开始排布。 + + ```ts + Flex({ direction: FlexDirection.RowReverse }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.png) - FlexDirection.Column:主轴为垂直方向,子组件从起始端沿着垂直方向开始排布。 - ```ts - Flex({ direction: FlexDirection.Column }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.png) - -- FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection.Column相反的方向开始排布。 - - ```ts - Flex({ direction: FlexDirection.ColumnReverse }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.png) - - -## 弹性布局换行 - -默认情况下,子组件在Flex容器中都排在一条线(又称"轴线")上。通过wrap参数设置其他换行方式,可选值有: - -- FlexWrap.NoWrap : 不换行。如果子元素的宽度总和大于父元素的宽度,则子元素会被压缩宽度。 - - ```ts - Flex({ wrap: FlexWrap.NoWrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.png) - -- FlexWrap.Wrap:换行。 - - ```ts - Flex({ wrap: FlexWrap.Wrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xD2B48C) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.png) - -- FlexWrap.WrapReverse:换行,且与行排列方向相反。 - - ```ts - Flex({ wrap: FlexWrap.WrapReverse}) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.png) - - -## 弹性布局对齐方式 - - -### 主轴对齐 - -可以通过justifyContent参数设置在主轴的对齐方式,可选值有: - -- FlexAlign.Start: 元素在主轴方向首端对齐, 第一个元素与行首对齐,同时后续的元素与前一个对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.Start }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218259634](figures/zh-cn_image_0000001218259634.png) - -- FlexAlign.Center: 元素在主轴方向中心对齐,第一个元素与行首的距离与最后一个元素与行尾距离相同。 - - ```ts - Flex({ justifyContent: FlexAlign.Center }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218579608](figures/zh-cn_image_0000001218579608.png) - -- FlexAlign.End: 元素在主轴方向尾部对齐, 最后一个元素与行尾对齐,其他元素与后一个对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.End }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218739568](figures/zh-cn_image_0000001218739568.png) - -- FlexAlign.SpaceBetween: Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。 第一个元素与行首对齐,最后一个元素与行尾对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceBetween }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263019461](figures/zh-cn_image_0000001263019461.png) - -- FlexAlign.SpaceAround: Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。 第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceAround }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263339461](figures/zh-cn_image_0000001263339461.png) - -- FlexAlign.SpaceEvenly: Flex主轴方向元素等间距布局, 相邻元素之间的间距、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceEvenly }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263139411](figures/zh-cn_image_0000001263139411.png) - - -### 交叉轴对齐 - -可以通过alignItems参数设置在交叉轴的对齐方式,可选值有: + ```ts + Flex({ direction: FlexDirection.Column }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.png) + +- FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection. Column相反的方向开始排布。 + + ```ts + Flex({ direction: FlexDirection.ColumnReverse }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.png) + +### 弹性布局换行 + +默认情况下,子组件在Flex容器中都排在一条线(又称"轴线")上。通过wrap参数设置子组件换行方式。可选值有: + +- FlexWrap. NoWrap(默认值): 不换行。如果子组件的宽度总和大于父元素的宽度,则子组件会被压缩宽度。 + + ```ts + Flex({ wrap: FlexWrap.NoWrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.png) + +- FlexWrap. Wrap:换行,每一行子组件按照主轴方向排列。 + + ```ts + Flex({ wrap: FlexWrap.Wrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xD2B48C) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.png) + +- FlexWrap. WrapReverse:换行,每一行子组件按照主轴反方向排列。 + + ```ts + Flex({ wrap: FlexWrap.WrapReverse}) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.png) + +### 弹性布局对齐方式 + +#### 主轴对齐 + +通过justifyContent参数设置在主轴方向的对齐方式,存在下面六种情况: + +![](figures/justifyContent.png) + +- FlexAlign.Start(默认值): 子组件在主轴方向起始端对齐, 第一个子组件与父元素边沿对齐,其他元素与前一个元素对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.Start }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218259634](figures/mainStart.png) + +- FlexAlign.Center: 子组件在主轴方向居中对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.Center }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218579608](figures/mainCenter.png) + +- FlexAlign.End: 子组件在主轴方向终点端对齐, 最后一个子组件与父元素边沿对齐,其他元素与后一个元素对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.End }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739568](figures/mainEnd.png) + +- FlexAlign.SpaceBetween: Flex主轴方向均匀分配弹性元素,相邻子组件之间距离相同。第一个子组件和最后一个子组件与父元素边沿对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019461](figures/mainSpacebetween.png) + +- FlexAlign.SpaceAround: Flex主轴方向均匀分配弹性元素,相邻子组件之间距离相同。第一个子组件到主轴起始端的距离和最后一个子组件到主轴终点端的距离是相邻元素之间距离的一半。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceAround }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263339461](figures/mainSpacearound.png) + +- FlexAlign.SpaceEvenly: Flex主轴方向元素等间距布局,相邻子组件之间的间距、第一个子组件与主轴起始端的间距、最后一个子组件到主轴终点端的间距均相等。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceEvenly }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263139411](figures/mainSpaceevenly.png) + +#### 交叉轴对齐 + +容器和子组件都可以设置交叉轴对齐方式,且子组件设置的对齐方式优先级较高。 + +##### 容器组件设置交叉轴对齐 +可以通过Flex组件的alignItems参数设置子组件在交叉轴的对齐方式,可选值有: - ItemAlign.Auto: 使用Flex容器中默认配置。 - ```ts - Flex({ alignItems: ItemAlign.Auto }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` + ```ts + Flex({ alignItems: ItemAlign.Auto }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` - ![zh-cn_image_0000001218419616](figures/zh-cn_image_0000001218419616.png) + ![zh-cn_image_0000001218419616](figures/zh-cn_image_0000001218419616.png) - ItemAlign.Start: 交叉轴方向首部对齐。 - ```ts - Flex({ alignItems: ItemAlign.Start }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263259401](figures/zh-cn_image_0000001263259401.png) + ```ts + Flex({ alignItems: ItemAlign.Start }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263259401](figures/zh-cn_image_0000001263259401.png) - ItemAlign.Center: 交叉轴方向居中对齐。 - ```ts - Flex({ alignItems: ItemAlign.Center }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218259636](figures/zh-cn_image_0000001218259636.png) + ```ts + Flex({ alignItems: ItemAlign.Center }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218259636](figures/zh-cn_image_0000001218259636.png) - ItemAlign.End:交叉轴方向底部对齐。 - ```ts - Flex({ alignItems: ItemAlign.End }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218579610](figures/zh-cn_image_0000001218579610.png) + ```ts + Flex({ alignItems: ItemAlign.End }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218579610](figures/zh-cn_image_0000001218579610.png) - ItemAlign.Stretch:交叉轴方向拉伸填充,在未设置尺寸时,拉伸到容器尺寸。 - ```ts - Flex({ alignItems: ItemAlign.Stretch }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218739570](figures/zh-cn_image_0000001218739570.png) + ```ts + Flex({ alignItems: ItemAlign.Stretch }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739570](figures/zh-cn_image_0000001218739570.png) + +- ItemAlign. Baseline:交叉轴方向文本基线对齐。 + + ```ts + Flex({ alignItems: ItemAlign.Baseline }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019463](figures/zh-cn_image_0000001263019463.png) + +##### 子组件设置交叉轴对齐 +子组件的alignSelf属性也可以设置子组件在父容器交叉轴的对齐格式,且会覆盖Flex布局容器中alignItems默认配置。如下例所示: -- ItemAlign.Baseline:交叉轴方向文本基线对齐。 +```ts +Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { //容器组件设置子组件居中 + Text('alignSelf Start').width('25%').height(80) + .alignSelf(ItemAlign.Start) + .backgroundColor(0xF5DEB3) + Text('alignSelf Baseline') + .alignSelf(ItemAlign.Baseline) + .width('25%') + .height(80) + .backgroundColor(0xD2B48C) + Text('alignSelf Baseline').width('25%').height(100) + .backgroundColor(0xF5DEB3) + .alignSelf(ItemAlign.Baseline) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xD2B48C) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xF5DEB3) + +}.width('90%').height(220).backgroundColor(0xAFEEEE) +``` +![](figures/alignself.png) + +上例中,Flex容器中alignItems设置交叉轴子组件的对齐方式为居中,子组件自身设置了alignSelf属性的情况,覆盖父组件的alignItem值,表现为alignSelf的定义。 + +#### 内容对齐 + +可以通过alignContent参数设置子组件各行在交叉轴剩余空间内的对齐方式,只在多行的flex布局中生效,可选值有: + +- FlexAlign.Start: 子组件各行与交叉轴起点对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Start }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossStart.png](figures/crossStart.png) + +- FlexAlign.Center: 子组件各行在交叉轴方向居中对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Center }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossCenter.png](figures/crossCenter.png) + +- FlexAlign.End: 子组件各行与交叉轴终点对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.End }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossEnd.png](figures/crossEnd.png) + +- FlexAlign.SpaceBetween: 子组件各行与交叉轴两端对齐,各行间垂直间距平均分布。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceBetween }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacebetween.png](figures/crossSpacebetween.png) + +- FlexAlign.SpaceAround: 子组件各行间距相等,是元素首尾行与交叉轴两端距离的两倍。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacearound.png](figures/crossSpacearound.png) + +- FlexAlign.SpaceEvenly: 子组件各行间距,子组件首尾行与交叉轴两端距离都相等。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpaceevenly.png](figures/crossSpaceevenly.png) + +### 弹性布局的自适应拉伸 + +在弹性布局父组件尺寸不够大的时候,通过子组件的下面几个属性设置其再父容器的占比,达到自适应布局能力。 +- flexBasis: 设置子组件在父容器主轴方向上的基准尺寸。如果设置了该值,则子项占用的空间为设置的值;如果没设置或者为auto,那子项的空间为width/height的值。 + ```ts - Flex({ alignItems: ItemAlign.Baseline }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) + Flex() { + Text('flexBasis("auto")') + .flexBasis('auto') // 未设置width以及flexBasis值为auto,内容自身宽松 + .height(100) + .backgroundColor(0xF5DEB3) + Text('flexBasis("auto")'+' width("40%")') + .width('40%') + .flexBasis('auto') //设置width以及flexBasis值auto,使用width的值 + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexBasis(100)') // 未设置width以及flexBasis值为100,宽度为100vp + .flexBasis(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexBasis(100)') + .flexBasis(100) + .width(200) // flexBasis值为100,覆盖width的设置值,宽度为100vp + .height(100) + .backgroundColor(0xD2B48C) + }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) ``` + + ![](figures/flexbasis.png) - ![zh-cn_image_0000001263019463](figures/zh-cn_image_0000001263019463.png) - +- flexGrow: 设置父容器的剩余空间分配给此属性所在组件的比例。用于"瓜分"父组件的剩余空间。 -### 内容对齐 - -可以通过alignContent参数设置在换行组件的行在交叉轴剩余空间内的对齐方式,可选值有: - -- FlexAlign.Start: 左对齐。 - -- FlexAlign.Center: 居中对齐。 - -- FlexAlign.End: 右对齐。 - -- FlexAlign.SpaceBetween: flex items之间的距离相等,与main start、main end两端对齐。 + ```ts + Flex() { + Text('flexGrow(1)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexGrow(3)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xD2B48C) + + Text('no flexGrow') + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexgrow.png) -- FlexAlign.SpaceAround: flex items之间的距离相等,flex items与main start、main end之间的距离等于flex items之间距离的一半。 +上图中,父容器宽度400vp, 三个子组件原始宽度为100vp,综合300vp,剩余空间100vp根据flexGrow值的占比分配给子组件,未设置flexGrow的子组件不参与“瓜分”。 +第一个元素以及第二个元素以2:3分配剩下的100vp。第一个元素为100vp+100vp*2/5=140vp,第二个元素为100vp+100vp*3/5=160vp。 -- FlexAlign.SpaceEvenly: flex items之间的距离相等,flex items与main start、main end之间的距离等于flex items之间的距离。 +- flexShrink: 当父容器空间不足时,子组件的压缩比例。 + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('flexShrink(3)') + .flexShrink(3) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('no flexShrink') + .width(200) + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexShrink(2)') + .flexShrink(2) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexshrink.png) ## 场景示例 - 可使用弹性布局做出子元素排列方式为水平方向排列,且子元素的总宽度超出父元素的宽度不换行,子元素在水平方向两端对齐,中间间距由除首尾外的子元素平分,竖直方向上子元素居中的效果。 +使用弹性布局,可以实现子组件沿水平方向排列,两端对齐,子组件间距平分,竖直方向上子组件居中的效果。示例如下: ```ts -@Entry +@Entry @Component struct FlexExample { build() { @@ -358,7 +567,6 @@ struct FlexExample { } .height(70) .width('90%') - .padding(10) .backgroundColor(0xAFEEEE) }.width('100%').margin({ top: 5 }) }.width('100%') @@ -366,9 +574,7 @@ struct FlexExample { } ``` - -![zh-cn_image_0000001261605867](figures/zh-cn_image_0000001261605867.png) - +![zh-cn_image_0000001261605867](figures/flexExample.png) ## 相关实例 diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md new file mode 100644 index 0000000000000000000000000000000000000000..c7346b6212432a1fec21def1f4bd81e719248568 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -0,0 +1,391 @@ +# 栅格布局 + +栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)和[GridCol](../reference/arkui-ts/ts-container-gridcol.md) +相对于[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)提供了更灵活、更全面的栅格系统实现方案。GridRow为栅格容器组件,只与栅格子组件GridCol在栅格布局场景中使用。 + + +## 栅格容器GridRow + + +栅格容器有columns、gutter、direction、breakpoints四个属性。 +- columns: 栅格布局的主要定位工具,设置栅格布局的总列数。 +- gutter: 设置元素之间的距离,决定内容间的紧密程度。 +- direction: 设置栅格子组件在栅格容器中的排列方向。 +- breakpoints:以设备宽度为基准,将应用宽度分成了几个不同的区间,即不同的断点。开发者可根据需要在不同的区间下实现不同的页面布局效果。 + + +首先通过设置断点,得到一系列断点区间;然后,借助栅格组件能力监听应用窗口大小的变化,判断应用当前处于哪个断点区间,最后调整应用的布局。 + +### 栅格系统断点 + +断点以设备宽度为基准,将应用宽度分成了几个不同的区间,即不同的断点。开发者根据需求在不同的区间实现不同的页面布局效果。 +[栅格系统默认断点](ui-ts-layout-grid-container.md#系统栅格断点)将设备宽度分为xs、sm、md、lg四类,尺寸范围如下: + +| 断点名称 | 取值范围(vp)| +| --------| ------ | +| xs | [0, 320) | +| sm | [320, 520) | +| md | [520, 840) | +| lg | [840, +∞) | + +在GridRow新栅格组件中,允许开发者使用breakpoints自定义修改断点的取值范围,最多支持6个断点,除了默认的四个断点外, +还可以启用xl,xxl两个断点,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的布局设置。 + +| 断点名称 | 设备描述 | +| ----- | ---------------------------------------- | +| xs | 最小宽度类型设备。 | +| sm | 小宽度类型设备。 | +| md | 中等宽度类型设备。 | +| lg | 大宽度类型设备。 | +| xl | 特大宽度类型设备。 | +| xxl | 超大宽度类型设备。 | + +- 针对断点位置,开发者根据实际使用场景,通过一个单调递增数组设置。由于breakpoints最多支持六个断点,单调递增数组长度最大为5。 + + ```ts + breakpoints: {value: ["100vp", "200vp"]} + ``` + + 表示启用xs、sm、md共3个断点,小于100vp为xs,100vp-200vp为sm,大于200vp为md。 + + ```ts + breakpoints: {value: ["320vp", "520vp", "840vp", "1080vp"]} + ``` + + 表示启用xs、sm、md、lg、xl共5个断点,小于320vp为xs,320vp-520vp为sm,520vp-840vp为md,840vp-1080vp为lg,大于1080vp为xl。 + + +- 栅格系统通过监听窗口或容器的尺寸变化进行断点,通过reference设置断点切换参考物。 考虑到应用可能以非全屏窗口的形式显示,以应用窗口宽度为参照物更为通用。 + +下例中,使用栅格的默认列数12列,通过断点设置将应用宽度分成六个区间,在各区间中,每个栅格子元素占用的列数均不同。效果如图: + ```ts +GridRow({ + breakpoints: { + value: ['200vp', '300vp', '400vp', '500vp', '600vp'], + reference: BreakpointsReference.WindowSize + } +}) { + ForEach(this.bgColors, (color, index) => { + GridCol({ + span: { + xs: 2, + sm: 3, + md: 4, + lg: 6, + xl: 8, + xxl: 12 + } + }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + }.backgroundColor(color) + }) +} +``` + +![](figures/breakpoints.gif) + + + +### 栅格布局的总列数 + +GridRow中通过columns设置栅格布局的总列数。 + +- columns默认值为12,当未设置columns时,在任何断点下,栅格布局被分成12列。 + ```ts + GridRow() { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + ``` + + ![](figures/columns1.png) + +- 当columns类型为number时,栅格布局在任何尺寸设备下都被分为columns列。下面分别设置栅格布局列数为4和8,子元素默认占一列,效果如下: + + ```ts + Row() { + GridRow({ columns: 4 }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + .width("100%").height("100%") + .onBreakpointChange((breakpoint) => { + this.currentBp = breakpoint + }) + } + .height(160) + .border({ color: Color.Blue, width: 2 }) + .width('90%') + + Row() { + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + .width("100%").height("100%") + .onBreakpointChange((breakpoint) => { + this.currentBp = breakpoint + }) + } + .height(160) + .border({ color: Color.Blue, width: 2 }) + .width('90%') + ``` + + ![](figures/columns2.png) + + +- 当columns类型为GridRowColumnOption时,支持下面六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的总列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow({ columns: { sm: 4, md: 8 }, breakpoints: { value: ['200vp', '300vp', '400vp', '500vp', '600vp'] } }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + ``` + ![](figures/columns3.gif) + + 如上,若只设置sm, md的栅格总列数,则较小的尺寸使用默认columns值12,较大的尺寸使用前一个尺寸的columns。这里只设置sm:8, md:10,则较小尺寸的xs:12,较大尺寸的参照md的设置,lg:10, xl:10, xxl:10。 + +### 栅格子组件间距 + +GridRow中通过gutter设置子元素在水平和垂直方向的间距。 + +- 当gutter类型为number时,同时设置栅格子组件间水平和垂直方向边距且相等。下例中,设置子组件水平与垂直方向距离相邻元素的间距为10。 + + ```ts + GridRow({ gutter: 10 }){} + ``` + + ![](figures/gutter1.png) + + + +- 当gutter类型为GutterOption时,单独设置栅格子组件水平垂直边距,x属性为水平方向间距,y为垂直方向间距。 + + ```ts + GridRow({ gutter: { x: 20, y: 50 } }){} + ``` + + ![](figures/gutter2.png) + + + +### 排列方向 + +通过GridRow的direction属性设置栅格子组件在栅格容器中的排列方向。 + +- 子组件默认从左往右排列。 + + ```ts + GridRow({ direction: GridRowDirection.Row }){} + ``` + ![](figures/direction1.png) + +- 子组件从右往左排列。 + + ```ts + GridRow({ direction: GridRowDirection.RowReverse }){} + ``` + + ![](figures/direction2.png) + + + +## 栅格子组件GridCol + +GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设置属性两种方式,设置span,offset,order的值。 + +- span的设置 + + ```ts + GridCol({ span: 2 }){} + GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }){} + GridCol(){}.span(2) + GridCol(){}.span({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + +- offset的设置 + + ```ts + GridCol({ offset: 2 }){} + GridCol({ offset: { xs: 2, sm: 2, md: 2, lg: 2 } }){} + GridCol(){}.offset(2) + GridCol(){}.offset({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + +- order的设置 + + ```ts + GridCol({ order: 2 }){} + GridCol({ order: { xs: 1, sm: 2, md: 3, lg: 4 } }){} + GridCol(){}.order(2) + GridCol(){}.order({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + + 下面使用传参的方式演示各属性的使用。 + +### span + +子组件占栅格布局的列数,决定了子组件的宽度,默认为1。 + +- 当类型为number时,子组件在所有尺寸设备下占用的列数相同。 + + ```ts + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (color, index) => { + GridCol({ span: 2 }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/span1.png) + +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件所占列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (color, index) => { + GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/span2.gif) + +### offset + +栅格子组件相对于前一个子组件的偏移列数,默认为0。 +- 当类型为number时,子组件偏移相同列数。 + + ```ts + GridRow() { + ForEach(this.bgColors, (color, index) => { + GridCol({ offset: 2 }) { + Row() { + Text("" + index) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/offset1.png) + + 栅格默认分成12列,每一个子组件默认占1列,偏移2列,每个子组件及间距共占3列,一行放四个子组件。 + + +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件所占列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow() { + ForEach(this.bgColors, (color, index) => { + GridCol({ offset: { xs: 1, sm: 2, md: 3, lg: 4 } }) { + Row() { + Text("" + index) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/offset2.gif) + +### order + + 栅格子组件的序号,决定子组件排列次序。当子组件不设置order或者设置相同的order, 子组件按照代码顺序展示。当子组件设置不同的order时,order较大的组件在前,较小的在后。 + 当子组件部分设置order,部分不设置order时,未设置order的子组件依次排序靠前,设置了order的子组件按照数值从大到小排列。 + + +- 当类型为number时,子组件在任何尺寸下排序次序一致。 + + ```ts + GridRow() { + GridCol({ order: 5 }) { + Row() { + Text("1") + }.width("100%").height("50vp") + }.backgroundColor(Color.Red) + GridCol({ order: 4 }) { + Row() { + Text("2") + }.width("100%").height("50vp") + }.backgroundColor(Color.Orange) + GridCol({ order: 3 }) { + Row() { + Text("3") + }.width("100%").height("50vp") + }.backgroundColor(Color.Yellow) + GridCol({ order: 2 }) { + Row() { + Text("4") + }.width("100%").height("50vp") + }.backgroundColor(Color.Green) + } + ``` + + ![](figures/order1.png) +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件排序次序设置。 + + ```ts + GridRow() { + GridCol({ order: { xs:1, sm:5, md:3, lg:7}}) { + Row() { + Text("1") + }.width("100%").height("50vp") + }.backgroundColor(Color.Red) + GridCol({ order: { xs:2, sm:2, md:6, lg:1} }) { + Row() { + Text("2") + }.width("100%").height("50vp") + }.backgroundColor(Color.Orange) + GridCol({ order: { xs:3, sm:3, md:1, lg:6} }) { + Row() { + Text("3") + }.width("100%").height("50vp") + }.backgroundColor(Color.Yellow) + GridCol({ order: { xs:4, sm:4, md:2, lg:5} }) { + Row() { + Text("4") + }.width("100%").height("50vp") + }.backgroundColor(Color.Green) + } + ``` + + ![](figures/order2.gif) + + diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md index dc0945724c0725d20d1be7da73790dd602fe71ca..420e594c188eead7944041bd6bffdde13e79c506 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md @@ -1,70 +1,76 @@ # 栅格布局 - 栅格系统作为一种辅助布局的定位工具,在平面设计和网站设计都起到了很好的作用,对移动设备的界面设计有较好的借鉴作用。总结栅格系统对于移动设备的优势主要有: - 1. 给布局提供一种可循的规律,解决多尺寸多设备的动态布局问题。 2. 给系统提供一种统一的定位标注,保证各模块各设备的布局一致性。 3. 给应用提供一种灵活的间距调整方法,满足特殊场景布局调整的可能性。 -为实现栅格布局效果,声明式范式提供了[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)栅格容器组件,配合其子组件的通用属性useSizeType来实现栅格布局。 +为实现栅格布局效果,声明式范式提供了[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)栅格容器组件,配合其子组件的通用属性[useSizeType](../reference/arkui-ts/ts-container-grid.md)来实现栅格布局。 ## 栅格系统 栅格系统有Column、Margin、Gutter三个概念。 - -![zh-cn_image_0000001217236574](figures/zh-cn_image_0000001217236574.png) - +![zh-cn_image_0000001224173302](figures/zh-cn_image_0000001224173302.png) 1. Gutter: - 用来控制元素与元素之间距离关系。可以根据设备的不同尺寸,定义不同的gutter值,作为栅格布局的统一规范。为了保证较好的视觉效果,通常gutter的取值不会大于margin的取值。 + 元素之间的距离,决定了内容间的紧密程度。作为栅格布局的统一规范。为了保证较好的视觉效果,通常gutter的取值不会大于margin的取值。 2. Margin: - 离栅格容器边缘的距离。可以根据设备的不同尺寸,定义不同的margin值,作为栅格布局的统一规范。 + 内容距栅格容器边缘的距离,决定了内容可展示的总宽度。作为栅格布局的统一规范。 3. Column: 栅格布局的主要定位工具。根据设备的不同尺寸,把栅格容器分割成不同的列数,在保证margin和gutter符合规范的情况下,根据总Column的个数计算每个Column列的宽度。 - ### 系统栅格断点 -系统根据不同水平宽度设备对应Column的数量关系,形成了一套断点规则定义。 - -系统以设备的水平宽度的屏幕密度像素值作为断点依据,根据当前设备水平宽度所在的断点范围,定义了设备的宽度类型。系统的栅格断点范围、设备宽度类型及其描述,以及对应的默认总列数(column),边距(margin),间隔(gutter)定义如下: +栅格系统以设备的水平宽度(屏幕密度像素值,vp)作为断点依据,定义设备的宽度类型,设置栅格总列数,间隔,边距,形成了一套断点规则。 +不同设备水平宽度下,栅格系统默认总列数(columns),边距(margin),间隔(gutter)定义如下: | 设备水平宽度断点范围 | 设备宽度类型 | 描述 | columns | gutter | margin | | ----------------------- | ------ | --------- | ------- | ------ | ------ | -| 0<水平宽度<320vp | XS | 最小宽度类型设备。 | 2 | 12vp | 12vp | -| 320vp<=水平宽度<600vp | SM | 小宽度类型设备。 | 4 | 24vp | 24vp | -| 600vp<=水平宽度<840vp | MD | 中等宽度类型设备。 | 8 | 24vp | 32vp | -| 840<=水平分辨率 | LG | 大宽度类型设备。 | 12 | 24vp | 48vp | +| 0< 水平宽度< 320vp | XS | 最小宽度类型设备。 | 2 | 12vp | 12vp | +| 320vp< =水平宽度< 600vp | SM | 小宽度类型设备。 | 4 | 24vp | 24vp | +| 600vp< =水平宽度< 840vp | MD | 中等宽度类型设备。 | 8 | 24vp | 32vp | +| 840< =水平分辨率 | LG | 大宽度类型设备。 | 12 | 24vp | 48vp | -## 如何使用 +> **说明:** +> +> ArkUI在API9对栅格组件做了重构,推出新的栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)和[GridCol](../reference/arkui-ts/ts-container-gridcol.md),API9推荐使用新的栅格组件,参考[新栅格组件用法](ui-ts-layout-grid-container-new.md) +> -首先创建栅格容器组件,定义栅格布局,然后给栅格容器内的组件设置不同设备宽度类型下的占用列数。 +## GridContainer栅格组件使用 -### 创建栅格容器 +首先使用栅格容器组件创建栅格布局。 -通过接口`GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})`创建栅格容器,栅格容器内的所有子组件可以使用栅格布局。 +### 栅格容器创建与设置 -- 可以通过参数定义栅格布局的总列数(columns),间隔(gutter),两侧边距(margin)。例如栅格容器总共分为6列,列与列间隔为10vp, 两侧边距为20vp: +通过接口 `GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})` 创建栅格容器,栅格容器内的所有子组件可以使用栅格布局。 - ```ts - GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} - ``` +通过参数定义栅格布局的总列数(columns),间隔(gutter),两侧边距(margin)。例如栅格容器总共分为6列,列与列间隔为10vp, 两侧边距为20vp: - 栅格容器不设置参数,或者sizeType设置为SizeType.Auto时使用默认的栅格系统定义,如: - ```ts - GridContainer() {} - ``` +```ts +GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} +``` - 上述例子中,默认在小宽度类型设备(SizeType.SM)上,栅格容器被分为4列,列与列的间隔为24vp, 两侧边距是24vp。在中等宽度类型设备(SizeType.MD)上,栅格容器被分为8列,列与列的间隔为24vp,两侧边距是32vp。 +栅格容器不设置参数,或者sizeType设置为SizeType. Auto时使用默认的栅格系统定义,如: -- 也可以通过参数sizeType指定此栅格容器内的组件使用此设备宽度类型的栅格设置,如: +```ts +GridContainer() {} +``` - ```ts +```ts +GridContainer({ sizeType: SizeType.Auto }) +``` + +上述例子中,默认在小宽度类型设备(SizeType. SM)上,栅格容器被分为4列,列与列的间隔为24vp, 两侧边距是24vp。在中等宽度类型设备(SizeType. MD)上,栅格容器被分为8列,列与列的间隔为24vp,两侧边距是32vp。 + +也可以通过参数sizeType指定此栅格容器内的组件使用此设备宽度类型的栅格设置,如: + + + +```ts GridContainer({ sizeType: SizeType.SM }) { Row() { Text('1') @@ -78,9 +84,9 @@ } ``` - 上述例子中,不管在任何宽度类型的设备上, Text组件都使用SizeType.SM类型的栅格设置即占用3列,放置在第1列。 + 上述例子中,不管在任何宽度类型的设备上, Text组件都使用SizeType. SM类型的栅格设置, 即占用3列,放置在第1列。 -### 栅格容器内子组件的栅格设置 +### 子组件的栅格设置 栅格容器中的组件使用通用属性useSizeType设置不同的设备宽度类型的占用列数和列偏移。其中span表示栅格容器组件占据columns的数量;offset表示列偏移量,指将组件放置在哪一个columns上。 如: @@ -97,13 +103,14 @@ GridContainer() { } } ``` -其中`sm: { span: 2, offset: 0 } `指在设备宽度类型为SM的设备上,Text组件占用2列,且放在栅格容器的第1列上。 + +其中 `sm: { span: 2, offset: 0 } ` 指在设备宽度类型为SM的设备上,Text组件占用2列,且放在栅格容器的第1列上。 ![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108719.png) ## 场景示例 -使用栅格布局可以灵活地在不同的设备宽度类型下呈现合适的效果,而不必书写大量的代码兼容不同宽度类型的设备。 +使用栅格布局可以灵活地在不同的设备宽度类型下呈现合适的效果,不必写大量的代码兼容不同宽度类型的设备。 ```ts @Entry @@ -144,11 +151,10 @@ struct GridContainerExample { } ``` - - -小宽度类型设备(SizeType.SM)运行效果: +小宽度类型设备(SizeType. SM)运行效果: ![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108718.png) -中等宽度类型设备(SizeType.MD)运行效果: +中等宽度类型设备(SizeType. MD)运行效果: + ![zh-cn_image_0000001262748569](figures/zh-cn_image_0000001262748569.png) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid.md b/zh-cn/application-dev/ui/ui-ts-layout-grid.md new file mode 100644 index 0000000000000000000000000000000000000000..69a9fde64de8d9cb79c0cb40c9f6d6eaba8ba757 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid.md @@ -0,0 +1,273 @@ +# 网格布局 + +网格布局(GridLayout)是自适应布局中一种重要的布局,具备较强的页面均分能力,子组件占比控制能力。 +通过[Grid](../reference/arkui-ts/ts-container-grid.md)容器组件和子组件[GridItem](../reference/arkui-ts/ts-container-griditem.md)实现, +Grid用于设置网格布局相关参数,GridItem定义子组件相关特征。优势如下: + +1. 容器组件尺寸发生变化时,所有子组件以及间距等比例调整,实现布局的自适应能力。 +2. 支持自定义网格布局行数和列数,以及每行每列尺寸占比。 +3. 支持设置网格布局中子组件的行列间距。 +4. 支持设置子组件横跨几行或者几列。 + + + +## 容器组件Grid设置 + +### 行列数量占比 +通过Grid的组件的columnsTemplate和rowTemplate属性设置网格布局行列数量与尺寸占比。 + +下面以columnsTemplate为例,介绍该属性的设置,该属性值是一个由多个空格和'数字+fr'间隔拼接的字符串,fr的个数即网格布局的列数,fr前面的数值大小,用于计算该列在网格布局宽度上的占比,最终决定该列的宽度。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3', '4'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('1fr 1fr 1fr 1fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了四个等分的列,每列宽度相等。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3', '4'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('1fr 2fr 3fr 4fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了四列,每列宽度比值为1:2:3:4。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('4fr 2fr 3fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了三列,每列宽度比值为4:2:3。 + +效果如下: + +![](figures/columnTemplate.png) + +### 排列方式 + +通过layoutDirection可以设置网格布局的主轴方向,决定子组件的排列方式。 +可选值包括Row,RowReverse, Column, ColumnReverse四种情况。 +效果如下: + +![](figures/gridlayout.png) + +### 行列间距 + +columnsGap用于设置网格子组件GridItem垂直方向的间距,rowsGap用于设置GridItem水平方向的间距。 + +```ts +Grid() +.columnsTemplate('1fr 1fr 1fr 1fr') +.columnsGap(10) +.rowsGap(20) +``` + +![](figures/columnGap.png) + +上图中,设置网格布局子组件间的垂直间距为20,水平间距为10。 + +## 网格子组件GridItem设置 + +### 设置子组件占的行列数 + +网格布局的行列标号从1开始,依次编号。 + +子组件横跨多行时,通过rowStart设置子组件起始行编号,rowEnd设置终点行编号。当rowStart值与rowEnd值相同时,子组件只占一个网格。示例如下: + +```ts +Grid() { + GridItem() { + Text('5') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.rowStart(2).rowEnd(3) // 5子组件从第二列到第三列 + + GridItem() { + Text('4') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(4).columnEnd(5) // 4从第四列到第五列 + + GridItem() { + Text('6') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(2).columnEnd(4) // 6从第二列到第四列 + + GridItem() { + Text('9') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(3).columnEnd(4) // 从第三列到第四列 +} +.columnsTemplate('1fr 1fr 1fr 1fr 1fr') +.rowsTemplate('1fr 1fr 1fr') +.columnsGap(10) +.rowsGap(20) +.width('90%') +.backgroundColor(0xF0F0F0) +.height('200vp') +.layoutDirection(GridDirection.Column) +``` + +![](figures/griditem.png) + +## 场景示例 + +使用grid布局实现一个计算器的排布效果,代码如下: + +```ts +@Entry +@Component +struct GridExample { + @State Number: Array = ['1', '2', '3', '+', '4', '5', '6', '-', '7', '8', '9', '*', '0', '.', '/'] + + @Styles textStyle(){ + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + + build() { + Column({ space: 5 }) { + Grid() { + GridItem() { + Text('0') + .fontSize(30) + .textStyle() + }.columnStart(1).columnEnd(4) + + GridItem() { + Text('清空') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(1).columnEnd(2) + + GridItem() { + Text('回退') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(3).columnEnd(4) + + ForEach(this.Number, (day: string) => { + if (day === '0') { + GridItem() { + Text(day) + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(1).columnEnd(2) + } else { + GridItem() { + Text(day) + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + } + } + }) + } + .columnsTemplate('1fr 1fr 1fr 1fr') + .rowsTemplate('2fr 1fr 1fr 1fr 1fr 1fr') + .columnsGap(10) + .rowsGap(15) + .width('90%') + .backgroundColor(0xF0F0F0) + .height('70%') + }.width('100%').margin({ top: 5 }) + } +} +``` + +在大屏设备上展示效果如下: + +![](figures/gridExp1.png) + +在小屏设备下展示效果如下: + +![](figures/gridExp2.png) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-linear.md b/zh-cn/application-dev/ui/ui-ts-layout-linear.md new file mode 100644 index 0000000000000000000000000000000000000000..0e89b56ad71bb008cae24b6b3151ea7464cd7862 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-linear.md @@ -0,0 +1,370 @@ +# 线性布局 + +线性布局(LinearLayout)是开发中最常用的布局。线性布局的子组件在线性方向上(水平方向和垂直方向)依次排列。 + +通过线性容器[Row](../reference/arkui-ts/ts-container-row.md)和[Column](../reference/arkui-ts/ts-container-column.md)实现线性布局。Column容器内子组件按照垂直方向排列,Row组件中,子组件按照水平方向排列。 + +## 线性布局的排列 + +线性布局的排列方向由所选容器组件决定。根据不同的排列方向,选择使用Row或Column容器创建线性布局,通过调整space,alignItems,justifyContent属性调整子组件的间距,水平垂直方向的对齐方式。 +1. 通过space参数设置主轴(排列方向)上子组件的间距。达到各子组件在排列方向上的等间距效果。 +2. 通过alignItems属性设置子组件在交叉轴(排列方向的垂直方向)的对齐方式。且在各类尺寸屏幕中,表现一致。其中,交叉轴为垂直方向时,取值为[VerticalAlign类型](../reference/arkui-ts/ts-appendix-enums.md#verticalalign),水平方向取值为[HorizontalAlign类型](../reference/arkui-ts/ts-appendix-enums.md#horizontalalign)。 +3. 通过justifyContent属性设置子组件在主轴(排列方向)上的对齐方式。实现布局的自适应均分能力。取值为[FlexAlign类型](../reference/arkui-ts/ts-appendix-enums.md#flexalign)。 + +具体使用以及效果如下表所示: + +|属性名|描述|Row效果图|Column效果图| +|------|---------------------------|----------------------------|---------------------------| +|space |- 横向布局中各子组件的在水平方向的间距
- 纵向布局中个子组件垂直方向间距| ![](figures/rowspace.png) | ![](figures/columnspace.png) | +|alignItems |容器排列方向的垂直方向上,子组件在父容器中的对齐方式|![](figures/rowalign.png) |![](figures/columnalign.png)| +|justifyContent |容器排列方向上,子组件在父容器中的对齐方式 |![](figures/rowjustify.png) |![](figures/columnjustify.png)| + +## 自适应拉伸 + +在线性布局下,常用空白填充组件[Blank](../reference/arkui-ts/ts-basic-components-blank.md),在容器主轴方向自动填充空白空间,达到自适应拉伸效果。 + +```ts +@Entry +@Component +struct BlankExample { + build() { + Column() { + Row() { + Text('Bluetooth').fontSize(18) + Blank() + Toggle({ type: ToggleType.Switch, isOn: true }) + }.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }).width('100%') + }.backgroundColor(0xEFEFEF).padding(20).width('100%') + } +} +``` + +![](figures/blank.gif) + +## 自适应缩放 + +自适应缩放是指在各种不同大小设备中,子组件按照预设的比例,尺寸随容器尺寸的变化而变化。在线性布局中有下列方法实现: + +1. 父容器尺寸确定时,设置了layoutWeight属性的子组件与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,在任意尺寸设备下,自适应占满剩余空间。 + + ```ts + @Entry + @Component + struct layoutWeightExample { + build() { + Column() { + Text('1:2:3').width('100%') + Row() { + Column() { + Text('layoutWeight(1)') + .textAlign(TextAlign.Center) + }.layoutWeight(2).backgroundColor(0xffd306).height('100%') + + Column() { + Text('layoutWeight(2)') + .textAlign(TextAlign.Center) + }.layoutWeight(4).backgroundColor(0xffed97).height('100%') + + Column() { + Text('layoutWeight(6)') + .textAlign(TextAlign.Center) + }.layoutWeight(6).backgroundColor(0xffd306).height('100%') + + }.backgroundColor(0xffd306).height('30%') + + Text('2:5:3').width('100%') + Row() { + Column() { + Text('layoutWeight(2)') + .textAlign(TextAlign.Center) + }.layoutWeight(2).backgroundColor(0xffd306).height('100%') + + Column() { + Text('layoutWeight(5)') + .textAlign(TextAlign.Center) + }.layoutWeight(5).backgroundColor(0xffed97).height('100%') + + Column() { + Text('layoutWeight(3)') + .textAlign(TextAlign.Center) + }.layoutWeight(3).backgroundColor(0xffd306).height('100%') + }.backgroundColor(0xffd306).height('30%') + } + } + } + ``` + + ![](figures/layoutWeight.gif) + + +3. 父容器尺寸确定时,使用百分比设置子组件以及兄弟组件的width宽度,可以保证各自元素在任意尺寸下的自适应占比。 + + ```ts + @Entry + @Component + struct WidthExample { + build() { + Column() { + Row() { + Column() { + Text('left width 20%') + .textAlign(TextAlign.Center) + }.width('20%').backgroundColor(0xffd306).height('100%') + + Column() { + Text('center width 50%') + .textAlign(TextAlign.Center) + }.width('50%').backgroundColor(0xffed97).height('100%') + + Column() { + Text('right width 30%') + .textAlign(TextAlign.Center) + }.width('30%').backgroundColor(0xffd306).height('100%') + }.backgroundColor(0xffd306).height('30%') + } + } + } + ``` + + ![](figures/width.gif) + + 上例中,在任意大小的设备中,子组件的宽度占比固定。 + +## 定位能力 +- 相对定位 + + 使用组件的[offset属性](../reference/arkui-ts/ts-universal-attributes-location.md)可以实现相对定位,设置元素相对于自身的偏移量。设置该属性,不影响父容器布局,仅在绘制时进行位置调整。使用线性布局和offset可以实现大部分布局的开发。 + + ```ts + @Entry + @Component + struct OffsetExample { + @Styles eleStyle() { + .size({ width: 120, height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + } + + build() { + Column({ space: 20 }) { + Row() { + Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('2 offset(15, 30)') + .eleStyle() + .fontSize(16) + .align(Alignment.Start) + .offset({ x: 15, y: 30 }) + Text('3').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('4 offset(-10%, 20%)') + .eleStyle() + .fontSize(16) + .offset({ x: '-5%', y: '20%' }) + }.width('90%').height(150).border({ width: 1, style: BorderStyle.Dashed }) + } + .width('100%') + .margin({ top: 25 }) + } + } + ``` + + ![](figures/offset.gif) + + +- 绝对定位 + + 线性布局中可以使用组件的[positon属性](../reference/arkui-ts/ts-universal-attributes-location.md)实现绝对布局(AbsoluteLayout),设置元素左上角相对于父容器左上角偏移位置。对于不同尺寸的设备,使用绝对定位的适应性会比较差,在屏幕的适配上有缺陷。 + + ```ts + @Entry + @Component + struct PositionExample { + @Styles eleStyle(){ + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .size({ width: 120, height: 50 }) + } + + build() { + Column({ space: 20 }) { + // 设置子组件左上角相对于父组件左上角的偏移位置 + Row() { + Text('position(30, 10)') + .eleStyle() + .fontSize(16) + .position({ x: 10, y: 10 }) + + Text('position(50%, 70%)') + .eleStyle() + .fontSize(16) + .position({ x: '50%', y: '70%' }) + + Text('position(10%, 90%)') + .eleStyle() + .fontSize(16) + .position({ x: '10%', y: '80%' }) + }.width('90%').height('100%').border({ width: 1, style: BorderStyle.Dashed }) + } + .width('90%').margin(25) + } + } + ``` + + ![](figures/position.gif) + + +## 自适应延伸 + +自适应延伸是在不同尺寸设备下,当页面显示内容个数不一并延伸到屏幕外时,可通过滚动条拖动展示。适用于线性布局中内容无法一屏展示的场景。常见以下两类实现方法。 + + +- List组件 + + List子项过多一屏放不下时,未展示的子项通过滚动条拖动显示。通过scrollBar属性设置滚动条的常驻状态,edgeEffect属性设置拖动到极限的回弹效果。 + + + 纵向List: + ```ts + @Entry + @Component + struct ListExample1 { + @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] + @State alignListItem: ListItemAlign = ListItemAlign.Start + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%') + .height(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .border({ width: 2, color: Color.Green }) + }, item => item) + } + .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) + .scrollBar(BarState.On) // 滚动条常驻 + .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 + + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) + } + } + ``` + + ![](figures/listcolumn.gif) + + + 横向List: + + ```ts + @Entry + @Component + struct ListExample2 { + @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] + @State alignListItem: ListItemAlign = ListItemAlign.Start + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .height('100%') + .width(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .border({ width: 2, color: Color.Green }) + }, item => item) + } + .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) + .scrollBar(BarState.On) // 滚动条常驻 + .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 + .listDirection(Axis.Horizontal) // 列表水平排列 + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) + } + } + ``` + + ![](figures/listrow.gif) + +- Scroll组件 + + 线性布局中,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。在Column或者Row外层包裹一个可滚动的容器组件Scroll实现。 + + 纵向Scroll: + + ```ts + @Entry + @Component + struct ScrollExample { + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + build() { + Scroll(this.scroller) { + Column() { + ForEach(this.arr, (item) => { + Text(item.toString()) + .width('90%') + .height(150) + .backgroundColor(0xFFFFFF) + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ top: 10 }) + }, item => item) + }.width('100%') + } + .backgroundColor(0xDCDCDC) + .scrollable(ScrollDirection.Vertical) // 滚动方向纵向 + .scrollBar(BarState.On) // 滚动条常驻显示 + .scrollBarColor(Color.Gray) // 滚动条颜色 + .scrollBarWidth(30) // 滚动条宽度 + .edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹 + } + } + ``` + + ![](figures/scrollcolumn.gif) + + 横向Scroll: + + ```ts + @Entry + @Component + struct ScrollExample { + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + build() { + Scroll(this.scroller) { + Row() { + ForEach(this.arr, (item) => { + Text(item.toString()) + .height('90%') + .width(150) + .backgroundColor(0xFFFFFF) + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ left: 10 }) + }, item => item) + }.height('100%') + } + .backgroundColor(0xDCDCDC) + .scrollable(ScrollDirection.Horizontal) // 滚动方向横向 + .scrollBar(BarState.On) // 滚动条常驻显示 + .scrollBarColor(Color.Gray) // 滚动条颜色 + .scrollBarWidth(30) // 滚动条宽度 + .edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹 + } + } + ``` + ![](figures/scrollrow.gif) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md index 27147d07fe719c98db76dd1a6ff57e3569a4faa6..100c4896116baa774b4f608a2764c356b5feef0c 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md @@ -1,27 +1,31 @@ # 媒体查询 +[媒体查询(Media Query)](../reference/apis/js-apis-mediaquery.md)作为响应式设计的核心,在移动设备上应用十分广泛。它根据不同设备类型或同设备不同状态修改应用的样式。媒体查询的优势有: -媒体查询(Media Query)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: +1. 提供丰富的媒体特征监听能力,针对设备和应用的属性信息(比如显示区域、深浅色、分辨率),设计出相匹配的布局。 +2. 当屏幕发生动态改变时(比如分屏、横竖屏切换),同步更新应用的页面布局。 -1. 针对设备和应用的属性信息,可以设计出相匹配的布局样式。 + -2. 当屏幕发生动态改变时(比如分屏、横竖屏切换),应用页面布局同步更新。 +## 媒体查询引入与使用流程 +媒体查询通过媒体查询接口,设置查询条件并绑定回调函数,在对应的条件的回调函数里更改页面布局或者实现业务逻辑,实现页面的响应式设计。具体步骤如下: -## 如何使用 +首先导入媒体查询模块。 -通过调用媒体查询接口,设置媒体查询条件和查询结果的回调函数,在对应的条件的回调函数里更改页面布局或者实现业务逻辑。 - -首先导入媒体查询模块,例如: -``` +```ts import mediaquery from '@ohos.mediaquery' ``` -然后通过matchMediaSync接口设置媒体查询条件,并保存返回的条件监听句柄,例如: + +通过matchMediaSync接口设置媒体查询条件,保存返回的条件监听句柄listener。 + ```ts listener = mediaquery.matchMediaSync('(orientation: landscape)') ``` -最后通过上面保存的条件监听句柄listener去注册回调函数,在回调函数里更改页面布局或者实现业务逻辑,当匹配到媒体查询条件时会触发此回调函数,例如: + +给条件监听句柄listener绑定回调函数onPortrait,当listener检测设备状态变化时执行回调函数。在回调函数内,根据不同设备状态更改页面布局或者实现业务逻辑。 + ```ts onPortrait(mediaQueryResult) { if (mediaQueryResult.matches) { @@ -33,19 +37,25 @@ onPortrait(mediaQueryResult) { listener.on('change', onPortrait) ``` -## 媒体查询条件语法规则 +## 媒体查询条件 + +媒体查询条件由媒体类型,逻辑操作符,媒体特征组成,其中媒体类型可省略,逻辑操作符用于连接不同媒体类型与媒体特征,其中,媒体特征要使用()包裹且可以有多个。具体规则如下: + +### 语法规则 + ``` [media-type] [and|not|only] [(media-feature)] ``` + 例如: -`screen and (round-screen: true)` :当设备屏幕是圆形时条件成立 +`screen and (round-screen: true)` :当设备屏幕是圆形时条件成立。 -`(max-height: 800)` :当高度小于800时条件成立 +`(max-height: 800)` :当高度小于等于800时条件成立。 -`(height <= 800) ` :当高度小于等于800时条件成立 +`(height <= 800) ` :当高度小于等于800时条件成立。 -`screen and (device-type: tv) or (resolution < 2)` :包含多个媒体特征的多条件复杂语句查询 +`screen and (device-type: tv) or (resolution < 2)` :包含多个媒体特征的多条件复杂语句查询,当设备类型为tv或设备分辨率小于2时条件成立。 ### 媒体类型(media-type) @@ -53,32 +63,30 @@ listener.on('change', onPortrait) | ------ | -------------- | | screen | 按屏幕相关参数进行媒体查询。 | +### 媒体逻辑操作(and|or|not|only) -### 媒体逻辑操作(and|not|only) - -媒体逻辑操作符:and、or、not、only用于构成复杂媒体查询,也可以通过comma(,)将其组合起来,详细解释说明如下表。 +媒体逻辑操作符:and、or、not、only用于构成复杂媒体查询,也可以通过comma(, )将其组合起来,详细解释说明如下表。 **表1** 媒体逻辑操作符 | 类型 | 说明 | | -------- | ---------------------------------------- | -| and | 将多个媒体特征(Media Feature)以“与”的方式连接成一个媒体查询,只有当所有媒体特征都为true,查询条件成立。另外,它还可以将媒体类型和媒体功能结合起来。
例如:screen and (device-type: wearable) and (max-height: 600) 表示当设备类型是智能穿戴同时应用的最大高度小于等于600个像素单位时成立。 | -| not | 取反媒体查询结果,媒体查询结果不成立时返回true,否则返回false。在媒体查询列表中应用not,则not仅取反应用它的媒体查询。
例如:not screen and (min-height: 50) and (max-height: 600) 表示当应用高度小于50个像素单位或者大于600个像素单位时成立。
使用not运算符时必须指定媒体类型。 | -| only | 当整个表达式都匹配时,才会应用选择的样式,可以应用在防止某些较早的版本的浏览器上产生歧义的场景。一些较早版本的浏览器对于同时包含了媒体类型和媒体特征的语句会产生歧义,比如:
screen and (min-height: 50)
老版本浏览器会将这句话理解成screen,从而导致仅仅匹配到媒体类型(screen),就应用了指定样式,使用only可以很好地规避这种情况。
使用only时必须指定媒体类型。 | -| ,(comma) | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。其效果等同于or运算符。
例如:screen and (min-height: 1000),  (round-screen:true) 表示当应用高度大于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | -| or | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。
例如:screen and (max-height: 1000) or  (round-screen:true)表示当应用高度小于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | +| and | 将多个媒体特征(Media  Feature)以“与”的方式连接成一个媒体查询,只有当所有媒体特征都为true,查询条件成立。另外,它还可以将媒体类型和媒体功能结合起来。
例如:screen  and  (device-type:  wearable)  and  (max-height:  600)  表示当设备类型是智能穿戴且应用的最大高度小于等于600个像素单位时成立。 | +| or | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。
例如:screen  and  (max-height:  1000)  or  (round-screen:true)表示当应用高度小于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | +| not | 取反媒体查询结果,媒体查询结果不成立时返回true,否则返回false。
例如:not  screen  and  (min-height:  50)  and  (max-height:  600)  表示当应用高度小于50个像素单位或者大于600个像素单位时成立。
使用not运算符时必须指定媒体类型。 | +| only | 当整个表达式都匹配时,才会应用选择的样式,可以应用在防止某些较早的版本的浏览器上产生歧义的场景。一些较早版本的浏览器对于同时包含了媒体类型和媒体特征的语句会产生歧义,比如:
screen  and  (min-height:  50)
老版本浏览器会将这句话理解成screen,从而导致仅仅匹配到媒体类型(screen),就应用了指定样式,使用only可以很好地规避这种情况。
使用only时必须指定媒体类型。 | +| , (comma) | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。其效果等同于or运算符。
例如:screen  and  (min-height:  1000),     (round-screen:true)  表示当应用高度大于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | -在MediaQuery Level 4中引入了范围查询,使其能够使用max-,min-的同时,也支持了<=,>=,<,>操作符。 +在MediaQuery Level 4中引入了范围查询,使其能够使用max-,min-的同时,也支持了< =,> =,< ,> 操作符。 **表2** 媒体逻辑范围操作符 | 类型 | 说明 | | ----- | ---------------------------------------- | -| <= | 小于等于,例如:screen and (50 <= height)。 | -| >= | 大于等于,例如:screen and (600 >= height)。 | -| < | 小于,例如:screen and (50 < height)。 | -| > | 大于,例如:screen and (600 > height)。 | - +| < = | 小于等于,例如:screen  and  (height  < =  50)。 | +| > = | 大于等于,例如:screen  and  (height  > =  600)。 | +| < | 小于,例如:screen  and  (height  <   50)。 | +| > | 大于,例如:screen  and  (height  >   600)。 | ### 媒体特征(media-feature) @@ -90,58 +98,59 @@ listener.on('change', onPortrait) | width | 应用页面显示区域的宽度。 | | min-width | 应用页面显示区域的最小宽度。 | | max-width | 应用页面显示区域的最大宽度。 | -| resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
- dpi表示每英寸中物理像素个数,1dpi≈0.39dpcm;
- dpcm表示每厘米上的物理像素个数,1dpcm ≈ 2.54dpi;
- dppx表示每个px中的物理像素数(此单位按96px=1英寸为基准,与页面中的px单位计算方式不同),1dppx = 96dpi。 | +| resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
-  dpi表示每英寸中物理像素个数,1dpi≈0.39dpcm;
-  dpcm表示每厘米上的物理像素个数,1dpcm  ≈  2.54dpi;
-  dppx表示每个px中的物理像素数(此单位按96px=1英寸为基准,与页面中的px单位计算方式不同),1dppx  =  96dpi。 | | min-resolution | 设备的最小分辨率。 | | max-resolution | 设备的最大分辨率。 | -| orientation | 屏幕的方向。
可选值:
- orientation: portrait(设备竖屏)
- orientation: landscape(设备横屏) | +| orientation | 屏幕的方向。
可选值:
-  orientation:  portrait(设备竖屏)
-  orientation:  landscape(设备横屏) | | device-height | 设备的高度。 | | min-device-height | 设备的最小高度。 | | max-device-height | 设备的最大高度。 | | device-width | 设备的宽度。 | | min-device-width | 设备的最小宽度。 | | max-device-width | 设备的最大宽度。 | -| round-screen | 屏幕类型,圆形屏幕为true, 非圆形屏幕为 false。 | +| round-screen | 屏幕类型,圆形屏幕为true,  非圆形屏幕为  false。 | | dark-mode | 系统为深色模式时为true,否则为false。 | ## 场景示例 -通过使用媒体查询实现当屏幕发生横竖屏切换,给页面文本应用不同的内容和样式。 - - ``` - import mediaquery from '@ohos.mediaquery' - let portraitFunc = null - - @Entry - @Component - struct MediaQueryExample { - @State color: string = '#DB7093' - @State text: string = 'Portrait' - @State fontSize: number = 24 - listener = mediaquery.matchMediaSync('(orientation: landscape)') - - onPortrait(mediaQueryResult) { - if (mediaQueryResult.matches) { - this.color = '#FFD700' - this.text = 'Landscape' - } else { - this.color = '#DB7093' - this.text = 'Portrait' - } - } - - aboutToAppear() { - portraitFunc = this.onPortrait.bind(this) //绑定当前应用实例 - this.listener.on('change', portraitFunc) +下例中使用媒体查询,实现屏幕横竖屏切换时给页面文本应用不同的内容和样式的效果。 + +```ts +import mediaquery from '@ohos.mediaquery' + +let portraitFunc = null + +@Entry +@Component +struct MediaQueryExample { + @State color: string = '#DB7093' + @State text: string = 'Portrait' + listener = mediaquery.matchMediaSync('(orientation: landscape)') // 当设备横屏时条件成立 + + onPortrait(mediaQueryResult) { + if (mediaQueryResult.matches) { + this.color = '#FFD700' + this.text = 'Landscape' + } else { + this.color = '#DB7093' + this.text = 'Portrait' } - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text(this.text).fontSize(50).fontColor(this.color) - } - .width('100%').height('100%') + } + + aboutToAppear() { + portraitFunc = this.onPortrait.bind(this) // 绑定当前应用实例 + this.listener.on('change', portraitFunc) + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(this.text).fontSize(50).fontColor(this.color) } + .width('100%').height('100%') } - ``` +} +``` + 横屏下文本内容为Landscape,颜色为#FFD700。 ![zh-cn_image_0000001262954829](figures/zh-cn_image_0000001262954829.png) @@ -152,7 +161,7 @@ listener.on('change', onPortrait) ## 相关实例 -针对媒体查询开发,有以下相关实例可供参考: +使用媒体查询的自适应布局开发,有以下相关实例可供参考: - [`MediaQuery`:媒体查询(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MediaQuery) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-stack.md b/zh-cn/application-dev/ui/ui-ts-layout-stack.md new file mode 100644 index 0000000000000000000000000000000000000000..63904bd277cea803b4c9147ebf618be26e561d02 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-stack.md @@ -0,0 +1,61 @@ +# 层叠布局 + +层叠布局(StackLayout)用于在屏幕上预留一块区域来显示组件中的元素,提供元素可以重叠的布局。 +通过层叠容器[Stack](../reference/arkui-ts/ts-container-stack.md)实现,容器中的子元素依次入栈,后一个子元素覆盖前一个子元素显示。 + +## 对齐方式 + +设置子元素在容器内的对齐方式。支持左上,上中,右上,左,中,右,右下,中下,右下九种对齐方式,如下表所示: + +|名称| 描述| 图示 | +|---| ---|---| +|TopStart| 顶部起始端 |![](figures/stacktopstart.png)| +Top |顶部横向居中 |![](figures/stacktop.png)| +TopEnd| 顶部尾端 |![](figures/stacktopend.png)| +Start| 起始端纵向居中 |![](figures/stackstart.png)| +Center| 横向和纵向居中 |![](figures/stackcenter.png)| +End| 尾端纵向居中 |![](figures/stackend.png)| +BottomStart |底部起始端 |![](figures/stackbottomstart.png)| +Bottom| 底部横向居中 |![](figures/stackbottom.png)| +BottomEnd| 底部尾端 |![](figures/stackbottomend.png)| + +## Z序控制 + +Stack容器中兄弟组件显示层级关系可以通过[zIndex](../reference/arkui-ts/ts-universal-attributes-z-order.md) +属性改变。zIndex值越大,显示层级越高,即zIndex值大的组件会覆盖在zIndex值小的组件上方。 + +- 在层叠布局中,如果后面子元素尺寸大于前面子元素尺寸,则前面子元素完全隐藏。 + + ```ts + Stack({ alignContent: Alignment.BottomStart }) { + Column() { + Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20) + }.width(100).height(100).backgroundColor(0xffd306) + Column() { + Text('Stack子元素2').fontSize(20) + }.width(150).height(150).backgroundColor(Color.Pink) + Column() { + Text('Stack子元素3').fontSize(20) + }.width(200).height(200).backgroundColor(Color.Grey) + }.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) + ``` + + ![](figures/stack2.png) + + 上图中,最后的子元素3的尺寸大于前面的所有子元素,所以,前面两个元素完全隐藏。改变子元素1,子元素2的zIndex属性后,可以将元素展示出来。 + + ```ts + Stack({ alignContent: Alignment.BottomStart }) { + Column() { + Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20) + }.width(100).height(100).backgroundColor(0xffd306).zIndex(2) + Column() { + Text('Stack子元素2').fontSize(20) + }.width(150).height(150).backgroundColor(Color.Pink).zIndex(1) + Column() { + Text('Stack子元素3').fontSize(20) + }.width(200).height(200).backgroundColor(Color.Grey) + }.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) + ``` + + ![](figures/stack1.png) diff --git a/zh-cn/application-dev/ui/ui-ts-overview.md b/zh-cn/application-dev/ui/ui-ts-overview.md index 348ce1cde17b33f3a6bb7fe393e74427f6852a63..e7bf1744db4373eb141e219dd19ca003782b82d8 100644 --- a/zh-cn/application-dev/ui/ui-ts-overview.md +++ b/zh-cn/application-dev/ui/ui-ts-overview.md @@ -1,30 +1,25 @@ # 概述 -基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、跨设备应用的UI开发框架,支持开发者高效的构建跨设备应用UI界面。 +基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、支持跨设备的UI开发框架,支持开发者高效地构建OpenHarmony应用UI界面。 ## 基础能力 -使用基于ArkTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动效和状态管理三个维度来提供UI能力,还提供了系统能力接口,实现系统能力的极简调用。 - -请参考[基于ArkTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解组件,更好地开发应用。 - +使用基于ArkTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动画和状态管理三个维度来提供UI能力,还提供了系统能力接口以实现系统能力的极简调用。 +ArkTS语言的基础知识请参考[学习ArkTS语言](../quick-start/arkts-get-started.md)文档;此外,请参考[基于ArkTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解内置组件,更好地开发应用。 - **开箱即用的组件** - 框架提供丰富的系统预置组件,可以通过链式调用的方式设置系统组件的渲染效果。开发者可以组合系统组件为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,使页面具有更强的工程性。 - + 框架提供丰富的系统内置组件,可以通过链式调用的方式设置系统组件的渲染效果。开发者可以组合系统组件为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,使页面具有更强的工程性。 - **丰富的动效接口** 提供svg标准的绘制图形能力,同时开放了丰富的动效接口,开发者可以通过封装的物理模型或者调用动画能力接口来实现自定义动画轨迹。 - - **状态与数据管理** 状态数据管理作为基于ArkTS的声明式开发范式的特色,通过功能不同的装饰器给开发者提供了清晰的页面更新渲染流程和管道。状态管理包括UI组件状态和应用程序状态,两者协作可以使开发者完整地构建整个应用的数据更新和UI渲染。 - - **系统能力接口** 使用基于ArkTS的声明式开发范式的方舟开发框架,还封装了丰富的系统能力接口,开发者可以通过简单的接口调用,实现从UI设计到系统能力调用的极简开发。 @@ -32,8 +27,6 @@ ## 整体架构 - - ![zh-cn_image_0000001169532276](figures/zh-cn_image_0000001169532276.png) - **声明式UI前端** @@ -50,7 +43,7 @@ - **渲染引擎** - 提供了高效的绘制能力,将渲染管线收集的渲染指令,绘制到屏幕能力。 + 提供了高效的绘制能力,将渲染管线收集的渲染指令,绘制到屏幕的能力。 - **平台适配层** @@ -61,18 +54,12 @@ 基于ArkTS的声明式开发范式的方舟开发框架,有以下相关实例可供参考: -- [`Canvas`:画布组件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Canvas) - - [`Drag`:拖拽事件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Drag) - [`ArkUIAnimation`:动画(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/ArkUIAnimation) -- [`Xcomponent`:XComponent(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/XComponent) - - [`MouseEvent`:鼠标事件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) -- [`Gallery`:组件集合(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) - - [`BringApp`:拉起系统应用(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/BringApp) - [`Chat`:聊天示例应用(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/AppSample/Chat) @@ -81,8 +68,6 @@ - [`Lottie`:Lottie(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Lottie) -- [`Clock`:简单时钟(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) - - [`Flybird`:小鸟避障游戏(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/Flybird) - [`AdaptiveCapabilities`:多设备自适应能力(ArkTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities) @@ -91,20 +76,12 @@ - [`TransitionAnimation`:转场动画(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/TransitionAnimation) -- [`PatternLock`:图案密码锁组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/PatternLock) - -- [`Search`:Search组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Search) - -- [`QRCode`:二维码(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/QRCode) - - [极简声明式UI范式(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts) - [购物应用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts) - [转场动画的使用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimtaionEts) -- [基础组件Slider的使用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderApplicationEts) - - [弹窗(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts) - [`UpgradePopup`:自定义弹窗(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/UpgradePopup) diff --git a/zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md b/zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md similarity index 94% rename from zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md rename to zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md index e37724ed2f5d44cf9557e36bcc072f7430a81658..8a0b469305af0bb990edc42c04ef09c7cf65f189 100644 --- a/zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md +++ b/zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md @@ -127,6 +127,8 @@ struct MyComponent { } ``` +![LazyForEach1](figures/LazyForEach1.gif) + 上述代码在页面加载时仅初始化加载三个列表元素,之后每点击一次列表元素,将增加一个列表元素。 ## 使用条件渲染替代显隐控制 @@ -179,6 +181,8 @@ struct MyComponent { } ``` +![isVisible](figures/isVisible.gif) + ## 使用Column/Row替代Flex 由于Flex容器组件默认情况下存在shrink导致二次布局,这会在一定程度上造成页面渲染上的性能劣化。 @@ -213,6 +217,8 @@ struct MyComponent { } ``` +![flex1](figures/flex1.PNG) + ## 设置List组件的宽高 开发者在使用Scroll容器组件嵌套List子组件时,若不指定List的宽高尺寸,则默认全部加载,如下所示: @@ -259,7 +265,10 @@ struct MyComponent { } ``` +![list1](figures/list1.gif) + ## 减少应用滑动白块 + 应用通过增大List/Grid控件的cachedCount参数,调整UI的加载范围。cachedCount表示屏幕外List/Grid预加载item的个数。 如果需要请求网络图片,可以在item滑动到屏幕显示之前,提前下载好内容,从而减少滑动白块。 如下是使用cachedCount参数的例子: @@ -269,33 +278,41 @@ struct MyComponent { @Component struct MyComponent { private source: MyDataSource = new MyDataSource(); + build() { List() { - LazyForEach (this.source, item => { + LazyForEach(this.source, item => { ListItem() { Text("Hello" + item) - .fontSize(100) - .onAppear(()=>{ + .fontSize(50) + .onAppear(() => { console.log("appear:" + item) }) } }) - }.cachedCount(3) // 扩大数值appear日志范围会变大 + }.cachedCount(3) // 扩大数值appear日志范围会变大 } } + class MyDataSource implements IDataSource { - data: number[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; + data: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + public totalCount(): number { return this.data.length } + public getData(index: number): any { return this.data[index] } + registerDataChangeListener(listener: DataChangeListener): void { } + unregisterDataChangeListener(listener: DataChangeListener): void { } } ``` +![list2](figures/list2.gif) + **使用说明:** cachedCount的增加会增大UI的cpu、内存开销。使用时需要根据实际情况,综合性能和用户体验进行调整。 \ No newline at end of file diff --git a/zh-cn/application-dev/webgl/webgl-overview.md b/zh-cn/application-dev/webgl/webgl-overview.md index 0ec7b58b040c6ce9d5cf108fa39038f8f7fc18fc..5333e869497c351587cd4aac55025e5a5db9a208 100644 --- a/zh-cn/application-dev/webgl/webgl-overview.md +++ b/zh-cn/application-dev/webgl/webgl-overview.md @@ -1,6 +1,6 @@ # 概述 -WebGL的全称为Web Graphic Library(网页图形库),主要用于交互式渲染2D图形和3D图形。目前OpenHarmony中使用的WebGL是基于OpenGL裁剪的OpenGL ES,可以在HTML5的canvas元素对象中使用,无需使用插件,支持跨平台。WebGL程序是由JavaScript代码组成的,其中使用的API可以利用用户设备提供的GPU硬件完成图形渲染和加速。 +WebGL的全称为Web Graphic Library(网页图形库),主要用于交互式渲染2D图形和3D图形。目前OpenHarmony中使用的WebGL是基于OpenGL裁剪的OpenGL ES,可以在HTML5的canvas元素对象中使用,无需使用插件,支持跨平台。WebGL程序是由JavaScript代码组成的,其中使用的API可以利用用户设备提供的GPU硬件完成图形渲染和加速。更多信息请参考[WebGL™标准](https://www.khronos.org/registry/webgl/specs/latest/1.0/)。 ## 基本概念 diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index e230026040d48d56d29db3e75377f0c479aa9fb3..96e02fdd8648a52265c6357090a4159af16f4ff9 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -1,18 +1,28 @@ # OpenHarmony应用开发文档 + - [应用开发导读](application-dev-guide.md) - 快速开始 - - 快速入门 - [开发准备](quick-start/start-overview.md) - - [使用eTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md) - - [使用eTS语言开发(FA模型)](quick-start/start-with-ets-fa.md) + - [使用ArkTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md) + - [使用ArkTS语言开发(FA模型)](quick-start/start-with-ets-fa.md) - [使用JS语言开发(FA模型)](quick-start/start-with-js-fa.md) - - 开发基础知识 - [应用包结构说明(FA模型)](quick-start/package-structure.md) - [应用包结构说明(Stage模型)](quick-start/stage-structure.md) - [SysCap说明](quick-start/syscap.md) - [HarmonyAppProvision配置文件](quick-start/app-provision-structure.md) + - 学习ArkTS语言 + - [初识ArkTS语言](quick-start/arkts-get-started.md) + - ArkTS语法(声明式UI) + - [基本UI描述](quick-start/arkts-basic-ui-description.md) + - 状态管理 + - [基本概念](quick-start/arkts-state-mgmt-concepts.md) + - [页面级变量的状态管理](quick-start/arkts-state-mgmt-page-level.md) + - [应用级变量的状态管理](quick-start/arkts-state-mgmt-application-level.md) + - [动态构建UI元素](quick-start/arkts-dynamic-ui-elememt-building.md) + - [渲染控制](quick-start/arkts-rendering-control.md) + - [使用限制与扩展](quick-start/arkts-restrictions-and-extensions.md) - 开发 - Ability开发 - [Ability框架概述](ability/ability-brief.md) @@ -37,7 +47,7 @@ - [测试框架使用指导](ability/ability-delegator.md) - UI开发 - [方舟开发框架(ArkUI)概述](ui/arkui-overview.md) - - 基于eTS的声明式开发范式 + - 基于ArkTS的声明式开发范式 - [概述](ui/ui-ts-overview.md) - 框架说明 - 文件组织 @@ -47,49 +57,10 @@ - [资源文件的分类](ui/ui-ts-basic-resource-file-categories.md) - [资源访问](ui/ts-resource-access.md) - [像素单位](ui/ts-pixel-units.md) - - 声明式语法 - - [描述规范使用说明](ui/ts-syntax-intro.md) - - 通用UI描述规范 - - [基本概念](ui/ts-general-ui-concepts.md) - - 声明式UI描述规范 - - [无构造参数配置](ui/ts-parameterless-configuration.md) - - [必选参数构造配置](ui/ts-configuration-with-mandatory-parameters.md) - - [属性配置](ui/ts-attribution-configuration.md) - - [事件配置](ui/ts-event-configuration.md) - - [子组件配置](ui/ts-child-component-configuration.md) - - 组件化 - - [@Component](ui/ts-component-based-component.md) - - [@Entry](ui/ts-component-based-entry.md) - - [@Preview](ui/ts-component-based-preview.md) - - [@Builder](ui/ts-component-based-builder.md) - - [@Extend](ui/ts-component-based-extend.md) - - [@CustomDialog](ui/ts-component-based-customdialog.md) - - [@Styles](ui/ts-component-based-styles.md) - - UI状态管理 - - [基本概念](ui/ts-ui-state-mgmt-concepts.md) - - 管理组件拥有的状态 - - [@State](ui/ts-component-states-state.md) - - [@Prop](ui/ts-component-states-prop.md) - - [@Link](ui/ts-component-states-link.md) - - 管理应用程序的状态 - - [应用程序的数据存储](ui/ts-application-states-appstorage.md) - - [Ability数据存储](ui/ui-ts-local-storage.md) - - [持久化数据管理](ui/ts-application-states-apis-persistentstorage.md) - - [环境变量](ui/ts-application-states-apis-environment.md) - - 其他类目的状态管理 - - [Observed和ObjectLink数据管理](ui/ts-other-states-observed-objectlink.md) - - [@Consume和@Provide数据管理](ui/ts-other-states-consume-provide.md) - - [@Watch](ui/ts-other-states-watch.md) - - 渲染控制语法 - - [条件渲染](ui/ts-rending-control-syntax-if-else.md) - - [循环渲染](ui/ts-rending-control-syntax-foreach.md) - - [数据懒加载](ui/ts-rending-control-syntax-lazyforeach.md) - 深入理解组件化 - - [build函数](ui/ts-function-build.md) - [自定义组件初始化](ui/ts-custom-component-initialization.md) - [自定义组件生命周期回调函数](ui/ts-custom-component-lifecycle-callbacks.md) - [组件创建和重新初始化示例](ui/ts-component-creation-re-initialization.md) - - [语法糖](ui/ts-syntactic-sugar.md) - 常见组件开发指导 - [Button开发指导](ui/ui-ts-basic-components-button.md) - [Web开发指导](ui/ui-ts-components-web.md) @@ -183,9 +154,6 @@ - [公共事件与通知概述](notification/notification-brief.md) - [公共事件开发指导](notification/common-event.md) - [通知开发指导](notification/notification-guidelines.md) - - 后台代理提醒 - - [后台代理提醒开发概述](notification/background-agent-scheduled-reminder-overview.md) - - [后台代理提醒开发指导](notification/background-agent-scheduled-reminder-guide.md) - [调试助手使用指导](notification/assistant-guidelines.md) - 窗口管理 - [窗口开发概述](windowmanager/window-overview.md) @@ -226,6 +194,9 @@ - 密钥管理 - [HUKS开发概述](security/huks-overview.md) - [HUKS开发指导](security/huks-guidelines.md) + - 加密算法库框架 + - [加密算法库框架概述](security/cryptoFramework-overview.md) + - [加密算法框架开发指导](security/cryptoFramework-guidelines.md) - Hap包签名工具 - [Hap包签名工具概述](security/hapsigntool-overview.md) - [Hap包签名工具指导](security/hapsigntool-guidelines.md) @@ -262,10 +233,13 @@ - 任务管理 - 后台任务 - [后台任务概述](task-management/background-task-overview.md) - - [后台任务开发指导](task-management/background-task-dev-guide.md) - - 延迟任务调度 - - [延迟任务调度概述](task-management/work-scheduler-overview.md) - - [延迟任务调度开发指导](task-management/work-scheduler-dev-guide.md) + - [短时任务开发指导](task-management/transient-task-dev-guide.md) + - [长时任务开发指导](task-management/continuous-task-dev-guide.md) + - [延迟任务开发指导](task-management/work-scheduler-dev-guide.md) + - [申请能效资源开发指导](task-management/efficiency-resources-apply-dev-guide.md) + - 后台代理提醒 + - [后台代理提醒开发概述](task-management/background-agent-scheduled-reminder-overview.md) + - [后台代理提醒开发指导](task-management/background-agent-scheduled-reminder-guide.md) - 设备管理 - USB服务 - [USB服务开发概述](device/usb-overview.md) @@ -333,18 +307,18 @@ - [资源](key-features/multi-device-app-dev/design-resources.md) - [工程管理](key-features/multi-device-app-dev/ide-using.md) - 页面开发的一多能力介绍 - - [简介](key-features/multi-device-app-dev/page-development-intro.md) - - 布局能力 - - [布局简介](key-features/multi-device-app-dev/layout-intro.md) - - [自适应布局](key-features/multi-device-app-dev/adaptive-layout.md) - - [响应式布局](key-features/multi-device-app-dev/responsive-layout.md) - - [典型布局场景](key-features/multi-device-app-dev/typical-layout-scenario.md) - - 典型页面场景 - - [应用市场首页](key-features/multi-device-app-dev/appgallery-home-page.md) - - [音乐专辑页](key-features/multi-device-app-dev/music-album-page.md) - - [交互归一](key-features/multi-device-app-dev/interaction-event-normalization.md) - - [多态组件](key-features/multi-device-app-dev/polymorphic-controls.md) - - [资源使用](key-features/multi-device-app-dev/resource-usage.md) + - [简介](key-features/multi-device-app-dev/page-development-intro.md) + - 布局能力 + - [布局简介](key-features/multi-device-app-dev/layout-intro.md) + - [自适应布局](key-features/multi-device-app-dev/adaptive-layout.md) + - [响应式布局](key-features/multi-device-app-dev/responsive-layout.md) + - [典型布局场景](key-features/multi-device-app-dev/typical-layout-scenario.md) + - 典型页面场景 + - [应用市场首页](key-features/multi-device-app-dev/appgallery-home-page.md) + - [音乐专辑页](key-features/multi-device-app-dev/music-album-page.md) + - [交互归一](key-features/multi-device-app-dev/interaction-event-normalization.md) + - [多态组件](key-features/multi-device-app-dev/polymorphic-controls.md) + - [资源使用](key-features/multi-device-app-dev/resource-usage.md) - [功能开发的一多能力介绍](key-features/multi-device-app-dev/development-intro.md) - [案例应用](key-features/multi-device-app-dev/case.md) - [常见问题](key-features/multi-device-app-dev/faq.md) @@ -354,7 +328,7 @@ - [Drawing开发指导](napi/drawing-guidelines.md) - [Rawfile开发指导](napi/rawfile-guidelines.md) - [Window开发指导](napi/native-window-guidelines.md) - - [使用MindSpore Lite引擎进行模型推理](napi/mindspore-lite-guidelines.md) + - [使用MindSpore Lite引擎进行模型推理](napi/mindspore-lite-guidelines.md) - 工具 - [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md) - 示例教程 @@ -362,7 +336,7 @@ - [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md) - API参考 - [Syscap列表](reference/syscap-list.md) - - 组件参考(基于eTS的声明式开发范式) + - 组件参考(基于ArkTS的声明式开发范式) - 组件通用信息 - 通用事件 - [点击事件](reference/arkui-ts/ts-universal-events-click.md) @@ -495,12 +469,12 @@ - 画布组件 - [Canvas](reference/arkui-ts/ts-components-canvas-canvas.md) - [CanvasRenderingContext2D对象](reference/arkui-ts/ts-canvasrenderingcontext2d.md) - - [OffscreenCanvasRenderingConxt2D对象](reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md) - - [Lottie](reference/arkui-ts/ts-components-canvas-lottie.md) - - [Path2D对象](reference/arkui-ts/ts-components-canvas-path2d.md) - [CanvasGradient对象](reference/arkui-ts/ts-components-canvas-canvasgradient.md) - [ImageBitmap对象](reference/arkui-ts/ts-components-canvas-imagebitmap.md) - [ImageData对象](reference/arkui-ts/ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingContext2D对象](reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md) + - [Path2D对象](reference/arkui-ts/ts-components-canvas-path2d.md) + - [Lottie](reference/arkui-ts/ts-components-canvas-lottie.md) - 动画 - [属性动画](reference/arkui-ts/ts-animatorproperty.md) - [显式动画](reference/arkui-ts/ts-explicit-animation.md) @@ -509,8 +483,7 @@ - [组件内转场](reference/arkui-ts/ts-transition-animation-component.md) - [共享元素转场](reference/arkui-ts/ts-transition-animation-shared-elements.md) - [路径动画](reference/arkui-ts/ts-motion-path-animation.md) - - [矩阵变换](reference/arkui-ts/ts-matrix-transformation.md) - - [插值计算](reference/arkui-ts/ts-interpolation-calculation.md) + - 全局UI方法 - 弹窗 - [警告弹窗](reference/arkui-ts/ts-methods-alert-dialog-box.md) @@ -711,6 +684,7 @@ - [@ohos.application.formInfo (FormInfo)](reference/apis/js-apis-formInfo.md) - [@ohos.application.formProvider (FormProvider)](reference/apis/js-apis-formprovider.md) - [@ohos.application.missionManager (missionManager)](reference/apis/js-apis-missionManager.md) + - [@ohos.application.quickFixManager (quickFixManager)](reference/apis/js-apis-application-quickFixManager.md) - [@ohos.application.Want (Want)](reference/apis/js-apis-application-Want.md) - [@ohos.continuation.continuationManager (ContinuationExtraParams)](reference/apis/js-apis-continuation-continuationExtraParams.md) - [@ohos.continuation.continuationManager (continuationManager)](reference/apis/js-apis-continuation-continuationManager.md) @@ -724,7 +698,7 @@ - [ProcessRunningInfo (ProcessRunningInfo)](reference/apis/js-apis-processrunninginfo.md) - [ProcessRunningInformation (ProcessRunningInformation)](reference/apis/js-apis-processrunninginformation.md) - [shellCmdResult (ShellCmdResult)](reference/apis/js-apis-application-shellCmdResult.md) - - [ContinuationResult (ContinuationResult)](reference/apis/js-apis-continuation-continuationResult.md) + - continuation/[ContinuationResult (ContinuationResult)](reference/apis/js-apis-continuation-continuationResult.md) - 公共事件与通知 - [@ohos.commonEvent (公共事件模块)](reference/apis/js-apis-commonEvent.md) - [@ohos.events.emitter (Emitter)](reference/apis/js-apis-emitter.md) @@ -751,10 +725,10 @@ - [LauncherAbilityInfo (LauncherAbilityInfo)](reference/apis/js-apis-bundle-LauncherAbilityInfo.md) - [Metadata (Metadata)](reference/apis/js-apis-bundle-Metadata.md) - [ModuleInfo (ModuleInfo)](reference/apis/js-apis-bundle-ModuleInfo.md) + - [PackInfo (PackInfo)](reference/apis/js-apis-bundle-PackInfo.md) - [PermissionDef (PermissionDef)](reference/apis/js-apis-bundle-PermissionDef.md) - [RemoteAbilityInfo (RemoteAbilityInfo)](reference/apis/js-apis-bundle-remoteAbilityInfo.md) - [ShortcutInfo (ShortcutInfo)](reference/apis/js-apis-bundle-ShortcutInfo.md) - - [PackInfo (PackInfo)](reference/apis/js-apis-bundle-PackInfo.md) - UI界面 - [@ohos.animator (动画)](reference/apis/js-apis-animator.md) - [@ohos.mediaquery (媒体查询)](reference/apis/js-apis-mediaquery.md) @@ -793,8 +767,8 @@ - 安全 - [@ohos.abilityAccessCtrl (访问控制管理)](reference/apis/js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (隐私管理)](reference/apis/js-apis-privacyManager.md) + - [@ohos.security.cryptoFramework (加密算法库框架)](reference/apis/js-apis-cryptoFramework.md) - [@ohos.security.huks (通用密钥库系统)](reference/apis/js-apis-huks.md) - - [@ohos.security.cryptoFramework (加解密算法库框架)](reference/apis/js-apis-cryptoFramework.md) - [@ohos.userIAM.faceAuth (人脸认证)](reference/apis/js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (用户认证)](reference/apis/js-apis-useriam-userauth.md) - [@system.cipher (加密算法)](reference/apis/js-apis-system-cipher.md) @@ -810,10 +784,11 @@ - [@ohos.data.ValuesBucket (数据集)](reference/apis/js-apis-data-ValuesBucket.md) - [resultSet (结果集)](reference/apis/js-apis-data-resultset.md) - 文件管理 + - [@ohos.data.fileAccess (公共文件访问与管理)](reference/apis/js-apis-fileAccess.md) - [@ohos.document (文件交互)](reference/apis/js-apis-document.md) - [@ohos.environment (目录环境能力)](reference/apis/js-apis-environment.md) + - [@ohos.fileExtensionInfo (公共文件访问与管理属性信息)](reference/apis/js-apis-fileExtensionInfo.md) - [@ohos.fileio (文件管理)](reference/apis/js-apis-fileio.md) - - [@ohos.fileManager (公共文件访问与管理)](reference/apis/js-apis-filemanager.md) - [@ohos.filemanagement.userfile_manager (用户数据管理)](reference/apis/js-apis-userfilemanager.md) - [@ohos.multimedia.medialibrary (媒体库管理)](reference/apis/js-apis-medialibrary.md) - [@ohos.securityLabel (数据标签)](reference/apis/js-apis-securityLabel.md) @@ -861,13 +836,13 @@ - [@ohos.hiSysEvent (系统事件打点)](reference/apis/js-apis-hisysevent.md) - [@ohos.hiTraceChain (分布式跟踪)](reference/apis/js-apis-hitracechain.md) - [@ohos.hiTraceMeter (性能打点)](reference/apis/js-apis-hitracemeter.md) - - [@ohos.inputMethod (输入法框架)](reference/apis/js-apis-inputmethod.md) - - [@ohos.inputMethodEngine (输入法服务)](reference/apis/js-apis-inputmethodengine.md) + - [@ohos.inputmethod (输入法框架)](reference/apis/js-apis-inputmethod.md) + - [@ohos.inputmethodengine (输入法服务)](reference/apis/js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability (InputMethodExtensionAbility)](reference/apis/js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext (InputMethodExtensionContext)](reference/apis/js-apis-inputmethod-extension-context.md) - [@ohos.pasteboard (剪贴板)](reference/apis/js-apis-pasteboard.md) - [@ohos.screenLock (锁屏管理)](reference/apis/js-apis-screen-lock.md) - - [@ohos.systemTime (系统时区、时间)](reference/apis/js-apis-system-time.md) + - [@ohos.systemTime (系统时间、时区)](reference/apis/js-apis-system-time.md) - [@ohos.systemTimer(系统定时器)](reference/apis/js-apis-system-timer.md) - [@ohos.wallpaper (壁纸)](reference/apis/js-apis-wallpaper.md) - [Timer (定时器)](reference/apis/js-apis-timer.md) @@ -949,6 +924,7 @@ - [@system.storage (数据存储)](reference/apis/js-apis-system-storage.md) - [@system.vibrator (振动)](reference/apis/js-apis-system-vibrate.md) - [console (日志打印)](reference/apis/js-apis-logs.md) + - 接口参考(Native API) - 模块 - [Native XComponent](reference/native-apis/_o_h___native_x_component.md) @@ -1018,7 +994,7 @@ - [full-SDK替换指南](quick-start/full-sdk-switch-guide.md) - [Ability框架开发常见问题](faqs/faqs-ability.md) - [UI框架(JS)开发常见问题](faqs/faqs-ui-js.md) - - [UI框架(eTS)开发常见问题](faqs/faqs-ui-ets.md) + - [UI框架(ArkTS)开发常见问题](faqs/faqs-ui-ets.md) - [图形图像开发常见问题](faqs/faqs-graphics.md) - [文件管理开发常见问题](faqs/faqs-file-management.md) - [网络与连接开发常见问题](faqs/faqs-connectivity.md) diff --git a/zh-cn/application-dev/windowmanager/application-window-fa.md b/zh-cn/application-dev/windowmanager/application-window-fa.md index aa71125a54912afbbd39c8537376c31b893d5f07..77a1755900cdc27ab3ff42aa094d77270c9a1e9e 100644 --- a/zh-cn/application-dev/windowmanager/application-window-fa.md +++ b/zh-cn/application-dev/windowmanager/application-window-fa.md @@ -27,7 +27,7 @@ | window静态方法 | find(id: string, callback: AsyncCallback<Window>): void | 查找`id`所对应的窗口。 | | Window | loadContent(path: string, callback: AsyncCallback<void>): void | 为当前窗口加载具体页面内容。 | | Window | moveTo(x: number, y: number, callback: AsyncCallback<void>): void | 移动当前窗口。 | -| Window | setBackgroundColor(color: string, callback: AsyncCallback<void>): void | 设置窗口的背景色 | +| Window | setBackgroundColor(color: string, callback: AsyncCallback<void>): void | 设置窗口的背景色。 | | Window | setBrightness(brightness: number, callback: AsyncCallback<void>): void | 设置屏幕亮度值。 | | Window | resetSize(width: number, height: number, callback: AsyncCallback<void>): void | 改变当前窗口大小。 | | Window | setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void | 设置窗口是否全屏显示。 | @@ -169,7 +169,7 @@ import window from '@ohos.window'; let mainWindowClass = null; - // 获取主窗口 + // 获取主窗口。 window.getTopWindow((err, data) => { if (err.code) { console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err)); @@ -218,10 +218,7 @@ let sysBarProps = { statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - // 以下两个属性从API Version7开始支持 - isStatusBarLightIcon: false, - isNavigationBarLightIcon: false, - // 以下两个属性从API Version8开始支持 + // 以下两个属性从API Version8开始支持。 statusBarContentColor: '#ffffff', navigationBarContentColor: '#ffffff' }; diff --git a/zh-cn/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md index 51b969f34e611a7a23ee8f115389590737b11a11..d6276679c8fd0a818b838b9c88ec0b6195af12c4 100644 --- a/zh-cn/application-dev/windowmanager/application-window-stage.md +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -258,9 +258,6 @@ class MainAbility extends Ability { let sysBarProps = { statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - // 以下两个属性从API Version 7开始支持 - isStatusBarLightIcon: false, - isNavigationBarLightIcon: false, // 以下两个属性从API Version 8开始支持 statusBarContentColor: '#ffffff', navigationBarContentColor: '#ffffff' diff --git "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" index 4006d5a1d8b7f384eb1169e6867b5f97d35b02ad..ae8a73e9c771c7a42ce662c325c43d4990f82182 100755 --- "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" +++ "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" @@ -10,7 +10,7 @@ [OpenHarmony安全设计规范](OpenHarmony-security-design-guide.md) -[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) +[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-buildsystem/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) ### 代码风格 diff --git a/zh-cn/device-dev/device-test/figures/FAQ-1.PNG b/zh-cn/device-dev/device-test/figures/FAQ-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..bebb315141c4cc3c004b502bb288705c8af9ebd8 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/FAQ-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/L0-1.PNG b/zh-cn/device-dev/device-test/figures/L0-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..35fb66bafc980f97f755d09f26ed682737d371a0 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/L0-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-1.PNG b/zh-cn/device-dev/device-test/figures/NFS-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..5fd5fb4f9063c00f1041eea1bb87b1b2519852cc Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-2.PNG b/zh-cn/device-dev/device-test/figures/NFS-2.PNG new file mode 100644 index 0000000000000000000000000000000000000000..0cd6f271936b2ee4fa97b256263bf85ba76c833b Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-2.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-3.PNG b/zh-cn/device-dev/device-test/figures/NFS-3.PNG new file mode 100644 index 0000000000000000000000000000000000000000..5a76e272ff763f3e31421d7c50c80f70febf1ce9 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-3.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/result-1.PNG b/zh-cn/device-dev/device-test/figures/result-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..64c730feade073029102459e92c01f8ff885f51d Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/result-1.PNG differ diff --git a/zh-cn/device-dev/device-test/xdevice.md b/zh-cn/device-dev/device-test/xdevice.md new file mode 100644 index 0000000000000000000000000000000000000000..54662ecf75e2248d40b287edba9ead3fc3f9e491 --- /dev/null +++ b/zh-cn/device-dev/device-test/xdevice.md @@ -0,0 +1,706 @@ +# xDevice测试调度执行框架使用指南 + + +## 概述 + +OpenHarmony开源操作系统有众多芯片场景基于其之上进行开发版本等相关产品的开发,为了保障OpenHarmony生态的兼容性,OpenHarmony提供了[兼容性测试测评服务](https://www.openharmony.cn/certification/document/guid),其中针对产品需要进行接口相关的测试执行验证,但是大量自动化用例的执行需要一套调度执行框架,并且支持生成可视化的测试报告等能力,故我们设计并开发了xdevice测试调度框架来支持该场景。 + +### 简介 + +xDevice测试调度框架是OpenHarmony中测试基础设施的核心组件,提供调度自动化用例执行所依赖的相关服务,支持大量自动化用例的调度执行能力,并可自带生成可视化测试报告。而xDevice二进制包会跟踪随OpenHarmony的XTS套件编译,开发者可以从XTS套件归档路径中获取xDevice工具, + +根据设备类型的不同,xDevice主要测试的任务场景有以下三个: + +- 对轻量系统设备进行XTS测试(如:Hi3861开发板) +- 对小型系统设备进行XTS测试(如:Hi3516开发板) +- 对标准系统设备进行XTS测试(如:RK3568开发板) + +### 实现原理 + +xDevice包括以下功能模块: + +- command:用户与测试平台命令行交互模块,提供用户输入命令解析,命令处理。 +- config:测试框架配置模块,提供测试平台串口连接方式和USB连接方式的不同配置选项。 +- driver:测试用例执行器,提供测试用例分发,执行,结果收集等主要测试步骤定义。 +- report:测试报告模块,提供测试结果解析和测试报告生成。 +- scheduler:测试框架调度模块,提供不同类型的测试执行器调度的调度功能。 +- environment:测试框架的环境配置模块,提供设备发现,设备管理的功能。 +- testkit:测试框架工具模块,提供json解析,网络文件挂载等操作。 +- log:测试框架日志模块,提供记录任务日志以及设备日志的功能。 + +除了上述功能模块之外,测试调度框架还依赖了用户自定义配置文件,配置文件主要分为两类。 + +**测试任务配置文件** + +user_config.xml是框架提供的测试任务配置文件,用户可以根据自身环境信息配置相关内容,主要包括以下配置内容。 + +environment环境相关配置,详解介绍如下。 + +```xml + + + + + + + + + + + + + + cmd + 115200 + 8 + 1 + 20 + + + + deploy + 115200 + + + + + + + + cmd + 115200 + 8 + 1 + 1 + + + + + + + + + +``` + +测试用例目录设置。 + +```xml + + + + + + + + + + + + + + + +``` + +资源目录设置。 + +```xml + + + + +``` + +日志打印级别设置。 + +```xml + +INFO +``` + +**测试套配置文件** + +设备执行的测试支撑套件是由测试配置文件所指定。 + +每个测试套都都有一个测试配置文件,主要配置了需要使用的测试支撑套件(kits)等信息,并支持配置执行预制和清理操作。 + +以下为配置文件样例。 + +```json +{ + // 测试支撑套件描述 + "description": "Configuration for aceceshi Tests", + + // 指定执行当前测试支撑套的设备 + "environment": { + "type": "device", + "label": "wifiiot" + }, + + // 指定设备执行的驱动 + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "700000", + "bundle-name": "com.open.harmony.acetestfive", + "package-name": "com.open.harmony.acetestfive", + "shell-timeout": "700000" + }, + // kit的作用主要是为了支撑测试执行活动,在测试前执行预制操作(Setup),在测试后执行清理操作(Teardown) + "kits": [ + { + "type": "ShellKit", + "run-command": [ + "remount", + "mkdir /data/data/resource", + "chmod -R 777 /data/data/resource", + "settings put secure adb_install_need_confirm 0" + ], + "teardown-command": [ + "remount", + "rm -rf /data/data/resource" + ] + }, + ] +} +``` + +### 测试命令 + +测试命令可以分为三组:help、list、run。在指令序列中,以run为最常用的执行指令。 + +------ + +输入help指令可以查询框架指令帮助信息。 + +```text +help: + use help to get information. +usage: + run: Display a list of supported run command. + list: Display a list of supported device and task record. +Examples: + help run + help list +``` + +**说明:** + +help run:展示run指令相关说明 。 + +help list:展示 list指令相关说明。 + +------ + +list指令用来展示设备和相关的任务信息。 + +```text +list: + This command is used to display device list and task record. +usage: + list + list history + list +Introduction: + list: display device list + list history: display history record of a serial of tasks + list : display history record about task what contains specific id +Examples: + list + list history + list 6e****90 +``` + + **说明:** + + list: 展示设备信息。 + + list history: 展示任务历史信息 。 + + list : 展示特定id的任务其历史信息。 + +------ + +run指令主要用于执行测试任务。 + +```text +run: + This command is used to execute the selected testcases. + It includes a series of processes such as use case compilation, execution, and result collection. +usage: run [-l TESTLIST [TESTLIST ...] | -tf TESTFILE + [TESTFILE ...]] [-tc TESTCASE] [-c CONFIG] [-sn DEVICE_SN] + [-rp REPORT_PATH [REPORT_PATH ...]] + [-respath RESOURCE_PATH [RESOURCE_PATH ...]] + [-tcpath TESTCASES_PATH [TESTCASES_PATH ...]] + [-ta TESTARGS [TESTARGS ...]] [-pt] + [-env TEST_ENVIRONMENT [TEST_ENVIRONMENT ...]] + [-e EXECTYPE] [-t [TESTTYPE [TESTTYPE ...]]] + [-td TESTDRIVER] [-tl TESTLEVEL] [-bv BUILD_VARIANT] + [-cov COVERAGE] [--retry RETRY] [--session SESSION] + [--dryrun] [--reboot-per-module] [--check-device] + [--repeat REPEAT] + action task +Specify tests to run. + positional arguments: + action Specify action + task Specify task name,such as "ssts", "acts", "hits" +``` + +run指令基本使用方法如下。 + +| xDevice命令 | 功能 | 示例 | +| :----------: | :----------------------------------------------------------: | :----------------------------------------------------------: | +| run xts | 运行所有指定类型的XTS模块,如acts,hits,ssys等 | run acts | +| run -l xxx | 运行指定的模块测试套,模块间用分号隔离 | run -l ActsWifiServiceTest;ActsLwipTest | +| run -sn | 指定运行设备的SN号,多个SN号用分号隔离 | run acts -sn 10.117.183.37:17001
run acts -sn 88Y02******57723;VEG02******16642 | +| run -rp | 指定报告生成的路径,默认会在工作目录的reports下用时间戳或任务ID建立子目录 | run acts -rp /suites/hits/xdevice_reports/2020.09.28-14.21.26 | +| run -respath | 指定测试资源路径,默认为resource目录 | run acts -respath /cloud/zidane/xts/release/suites/resource | +| run -ta | 指定模块运行参数,可以指定运行模块用例中指定的用例,多个用例用逗号隔离,目前支持JS驱动测试套 | run acts -ta class:ohos.hardware.soundtrigger.SoundTriggerTest#testKeyphraseParcelUnparcel_noUsers | +| run --retry | 重新运行上一次任务的失败用例,生成新的测试报告 | run –retryrun --retry --session 2020-10-30-17-15-11(任务目录名) | + +### 测试报告 + +框架执行run指令,控制台会输出对应的log打印,还会生成对应的执行结果报告。如果使用了-rp参数指定报告路径,那么报告就会生成在指定的路径下。否则报告会存放在默认目录。 + +```text +当前报告目录(默认目录/指定目录) + ├── result(模块执行结果存放目录) + │ ├── <模块名>.xml + │ ├── ... ... + │ + ├── log (设备和任务运行log存放目录) + │ ├── <设备1>.log + │ ├── ... ... + │ ├── <任务>.log + ├── summary_report.xml(任务汇总数据报告) + ├── summary_report.html(任务汇总可视化报告) + ├── details_report.html(用例执性可视化报告) + ├── failures_report.html(失败用例可视化报告,无失败用例时不生成) + ├── summary.ini(记录测试类型,使用的设备,开始和结束时间等信息) + ├── task_info.record(记录执行命令,失败用例清单等信息) + ├── xxxx.zip(对上述文件进行压缩得到的压缩文件) + ├── summary_report.hash(对压缩文件进行sha256加密得到的文件) + └── ... ... +``` + + +## 环境准备 + + +### 环境要求 + +- python版本>=3.7 +- pyserial>=3.3 +- paramiko>=2.7.1 +- rsa>=4.0 + + +### 安装xDevice + +- 安装基础框架xDevice。 + + 1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + + 2. 打开控制台,执行如下命令。 + + ```bash + python setup.py install + ``` + +- 安装OpenHarmony驱动插件ohos。 + + 1. 进行plugin/ohos目录。 + + ```bash + cd testfwk_xdevice/plugin/ohos + ``` + + 2. 打开控制台,当前用户下执行如下命令。 + + ```bash + python setup.py install + ``` + +### 检验环境是否搭建成功 + +检验xDevice是否安装成功。 + +1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + +2. 打开控制台,执行如下命令。 + + ```bash + python -m pip list + ``` + +3. 查看是否已经成功安装**xdevice**以及**xdevice-ohos**两个库。 + + ```text + xdevice 0.0.0 + xdevice-ohos 0.0.0 + ``` + +查看xDevice工具是否能够正常运行。 + +1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + +2. 打开控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + +3. 查看控制台是否正常输出如下信息。 + + ```text + [2022-10-13 15:43:31,284] [30076] [Main] [INFO] [*************** xDevice Test Framework 2.11.0.1091 Starting ***************] + [2022-10-13 15:43:31,286] [30076] [ManagerLite] [WARNING] [wifiiot local com cannot be empty, please check] + [2022-10-13 15:43:31,286] [30076] [ManagerLite] [WARNING] [ipcamera local com cannot be empty, please check] + [2022-10-13 15:43:31,287] [30076] [ManagerLite] [WARNING] [device com or ip cannot be empty, please check] + >>> + ``` + + +## 轻量系统设备XTS测试指导(wifiiot) + +1. 识别串口用途,修改根目录中的user_config.xml文件。 + + type为cmd的com口对应板子上的AT命令串口,用于对设备发送指令,示例中配置为ChA(COM20)串口号。 + + type为deploy的com口对应板子上的日志输出串口,用于镜像烧录和日志打印,示例中配置为ChB(COM18)串口号。 + + 若AT命令串口和日志输出串口共用,可以配置为相同,即user_config中的type为cmd的com口与type为deploy的com口可配置为一样的端口,如COM18。 + + ![L0-1](figures/L0-1.PNG) + + user_config.xml的修改示例如下。 + + ```xml + + + + + com20 + cmd + 115200 + 8 + 1 + 20 + + + com18 + deploy + 115200 + + + + + + + + + + + + + + + + + + DEBUG + + ``` + +2. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建中获取。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Config for ActsAllTest test cases", + "environment": [ + { + "type": "device", + "label": "wifiiot" + } + ], + "kits": [ + { + "type": "DeployKit", + "timeout": "20000", + "burn_file": "acts/Hi3861_wifiiot_app_allinone.bin" + } + ], + "driver": { + "type": "CTestLite" + } + } + ``` + +3. 执行用例 + + 进入xDevice根目录;打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l ActsAllTest + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 小型系统设备XTS测试指导(ipcamera) + +1. 识别串口用途。 + + type为cmd的com口对应板子上的AT命令串口,用于对设备发送指令,示例中配置为ChA(COM20)串口号。 + + L0-1 + + ipcamera设备有两种连接方式,一种是本地串口连接,一种是通过局域网ip连接。 + +2. 配置NFS服务器 + + NFS挂载方式有两种,一种是远程PC挂载方式,一种是本地局域网挂载方式。 + + 本地局域网NFS服务的配置方法如下。 + + 1. 下载安装NFS服务器。下载地址:https://www.hanewin.net/nfs-e.htm + + 2. 配置输出->编辑输出表文件。 + + + + 3. 添加路径NFS共享路径(如:D:\HS\NFS_Share_File -public –alldirs),这里要注意ftp的IP地址192.168.1.10为开发板的IP。 + + + + 4. 停止NFS服务器->重启运行NFS服务器使刚才添加的共享路径生效。 + + 5. 找到ipcamera设备在PC上面映射的网口:控制面板->网络和Internet->网络共享中心->以太网状态->以太网属性->手动设置IP地址为:192.168.1.11。 + + + +3. 修改根目录中的user_config.xml文件,示例如下。 + + ```xml + + + + + com20 + cmd + 115200 + 8 + 1 + 1 + + + + 10.176.49.47 + 10003 + + + + + + 10.176.48.202 + 1022 + /data/data/local/ + root + xxx + true + + + 192.168.1.11 + 2049 + D:\test + false + + + + + + DEBUG + + ``` + +4. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Config for kernel test cases", + "environment": [ + { + "type": "device", + "label": "ipcamera" + } + ], + "kits": [ + { + "type": "MountKit", + "server": "NfsServer", + "mount": [ + { + "source": "testcases/kernel", + "target": "/test_root/kernel" + } + ] + } + ], + "driver": { + "type": "CppTestLite", + "excute": "/test_root/kernel/ActsKernelIPCTest.bin" + } + } + ``` + +5. 执行用例。 + + 进入xDevice根目录,打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l kernel + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 标准系统设备XTS测试指导(RK3568) + +1. 配置hdc工具,从每日构建上下载ohos_sdk最新版本即可。 + + 每日构建地址:http://ci.openharmony.cn/dailys/dailybuilds + + 下载工具后,把hdc配置到环境变量中,配置方法:右键单击我的电脑->属性->高级系统设置->环境变量->Path。 + +2. 执行如下命令查看设备是否正常连接。 + + ```bash + hdc_std list targets + ``` + +3. 修改user_config.xml文件,示例如下。 + + ```xml + + + + + + xxx;xxx + + + + + + + + + DEBUG + + ``` + +4. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建中获取。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Configuration for hjunit demo Tests", + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "180000", + "bundle-name": "ohos.acts.bundle.stage.test", + "module-name": "phone", + "shell-timeout": "600000", + "testcase-timeout": 70000 + }, + "kits": [ + { + "test-file-name": [ + "ActBmsStageEtsTest.hap" + ], + "type": "AppInstallKit", + "cleanup-apps": true + }, + { + "type": "ShellKit", + "teardown-command":[ + "bm uninstall -n ohos.acts.bundle.stage.test" + ] + } + ] + } + ``` + +5. 执行用例。 + + 进入xDevice根目录,打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l ActBmsStageEtsTest + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 常见问题 + +### hdc list targets能查找到设备,但xDevice识别不到设备。 + +**问题描述** + +出现如下错误。 + +![FAQ-1](figures/FAQ-1.PNG) + +**可能原因** + +环境变量中曾设置过HDC_SERVER_PORT变量修改过hdc的端口,由于xDevice默认需要使用8710端口,若曾修改过该端口会导致xDevice框架无法识别设备。 + +**解决方法** + +检查是否有设置HDC_SERVER_PROT变量,若有设置,请把该端口的值修改为8710,然后重启xDevice即可。 + diff --git a/zh-cn/device-dev/driver/Readme-CN.md b/zh-cn/device-dev/driver/Readme-CN.md index 2ec6342f1047f5684fdba52354d18eb49e4dbe28..38a7a307b5cefbf534863ef3347f098307b732c3 100755 --- a/zh-cn/device-dev/driver/Readme-CN.md +++ b/zh-cn/device-dev/driver/Readme-CN.md @@ -4,6 +4,7 @@ - HDF驱动框架 - [HDF开发概述](driver-hdf-overview.md) - [驱动开发](driver-hdf-development.md) + - [驱动加载](driver-hdf-load.md) - [驱动服务管理](driver-hdf-servicemanage.md) - [驱动消息机制管理](driver-hdf-message-management.md) - [配置管理](driver-hdf-manage.md) diff --git a/zh-cn/device-dev/driver/driver-hdf-development.md b/zh-cn/device-dev/driver/driver-hdf-development.md index c1abcd7db00abc914a482303583e2ac49520c597..2586488b13e1bac6fa003cdb58e543ecbfa7c785 100755 --- a/zh-cn/device-dev/driver/driver-hdf-development.md +++ b/zh-cn/device-dev/driver/driver-hdf-development.md @@ -3,7 +3,7 @@ ## 驱动模型介绍 -HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心设计思路,为开发者提供更精细化的驱动管理,让驱动开发和部署更加规范。HDF框架将一类设备驱动放在同一个Host里面,开发者也可以将驱动功能分层独立开发和部署,支持一个驱动多个Node。HDF驱动模型如下图所示: +HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心设计思路,为开发者提供更精细化的驱动管理,让驱动开发和部署更加规范。HDF框架将一类设备驱动放在同一个Host(设备容器)里面,用于管理一组设备的启动加载等过程。在划分Host时,驱动程序是部署在一个Host还是部署在不同的Host,主要考虑驱动程序之间是否存在耦合性,如果两个驱动程序之间存在依赖,可以考虑将这部分驱动程序部署在一个Host里面,否则部署到独立的Host中是更好的选择。Device对应一个真实的物理设备。DeviceNode是设备的一个部件,Device至少有一个DeviceNode。每个DeviceNode可以发布一个设备服务。驱动即驱动程序,每个DevicdNode唯一对应一个驱动,实现和硬件的功能交互。HDF驱动模型如下图所示: **图1** HDF驱动模型 @@ -12,7 +12,7 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 ## 驱动开发步骤 -基于HDF框架的驱动开发主要分为三个部分:驱动实现、驱动编译和驱动配置。详细开发流程如下所示: +基于HDF框架的驱动开发主要分为三个部分:驱动实现、驱动编译脚本编写和驱动配置。详细开发流程如下所示: 1. 驱动实现 @@ -20,24 +20,24 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 - 驱动业务代码 - ``` + ```c #include "hdf_device_desc.h" // HDF框架对驱动开发相关能力接口的头文件 #include "hdf_log.h" // HDF框架提供的日志接口头文件 - #define HDF_LOG_TAG "sample_driver" // 打印日志所包含的标签,如果不定义则用默认定义的HDF_TAG标签。 + #define HDF_LOG_TAG sample_driver // 打印日志所包含的标签,如果不定义则用默认定义的HDF_TAG标签。 - // 驱动对外提供的服务能力,将相关的服务接口绑定到HDF框架。 + // 将驱动对外提供的服务能力接口绑定到HDF框架。 int32_t HdfSampleDriverBind(struct HdfDeviceObject *deviceObject) { HDF_LOGD("Sample driver bind success"); - return 0; + return HDF_SUCCESS; } // 驱动自身业务初始化的接口 int32_t HdfSampleDriverInit(struct HdfDeviceObject *deviceObject) { HDF_LOGD("Sample driver Init success"); - return 0; + return HDF_SUCCESS; } // 驱动资源释放的接口 @@ -49,7 +49,7 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 ``` - 驱动入口注册到HDF框架 - ``` + ```c // 定义驱动入口的对象,必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量。 struct HdfDriverEntry g_sampleDriverEntry = { .moduleVersion = 1, @@ -63,7 +63,7 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 HDF_INIT(g_sampleDriverEntry); ``` -2. 驱动编译 +2. 驱动编译脚本编写 - LiteOS @@ -74,8 +74,8 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 驱动代码的编译必须要使用HDF框架提供的Makefile模板进行编译。 - ``` - include $(LITEOSTOPDIR)/../../drivers/adapter/khdf/liteos/lite.mk # 【必需】导入hdf预定义内容 + ```c + include $(LITEOSTOPDIR)/../../drivers/hdf_core/adapter/khdf/liteos/lite.mk # 【必需】导入hdf预定义内容 MODULE_NAME := #生成的结果文件 LOCAL_INCLUDE := #本驱动的头文件目录 LOCAL_SRCS := #本驱动的源代码文件 @@ -83,22 +83,22 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 include $(HDF_DRIVER) #导入Makefile模板完成编译 ``` - 编译结果文件链接到内核镜像,添加到**drivers/adapter/khdf/liteos**目录下的**hdf_lite.mk**里面,示例如下: + 编译结果文件链接到内核镜像,添加到**drivers/hdf_core/adapter/khdf/liteos**目录下的**hdf_lite.mk**里面,示例如下: - ``` + ```c LITEOS_BASELIB += -lxxx #链接生成的静态库 LIB_SUBDIRS += #驱动代码Makefile的目录 ``` - BUILD.gn部分: - 添加模块BUILD.gn参考定义如下内容: + 添加模块BUILD.gn,可参考如下示例: - ``` + ```c import("//build/lite/config/component/lite_component.gni") - import("//drivers/adapter/khdf/liteos/hdf.gni") + import("//drivers/hdf_core/adapter/khdf/liteos/hdf.gni") module_switch = defined(LOSCFG_DRIVERS_HDF_xxx) module_name = "xxx" hdf_driver(module_name) { @@ -109,42 +109,42 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 } config("public") { #定义依赖的头文件配置 include_dirs = [ - "xxx/xxx/xxx", #依赖的头文件目录 + "xxx/xxx/xxx", #依赖的头文件目录 ] } ``` - 把新增模块的BUILD.gn所在的目录添加到**/drivers/adapter/khdf/liteos/BUILD.gn**里面: + 把新增模块的BUILD.gn所在的目录添加到**/drivers/hdf_core/adapter/khdf/liteos/BUILD.gn**里面: - ``` + ```c group("liteos") { public_deps = [ ":$module_name" ] deps = [ - "xxx/xxx", #新增模块BUILD.gn所在的目录,目录结构相对于/drivers/adapter/khdf/liteos + "xxx/xxx", #新增模块BUILD.gn所在的目录,目录结构相对于/drivers/hdf_core/adapter/khdf/liteos ] } ``` - Linux - 如果需要定义模块控制宏,需要在模块目录xxx里面添加Kconfig文件,并把Kconfig文件路径添加到**drivers/adapter/khdf/linux/Kconfig**里面: + 如果需要定义模块控制宏,需要在模块目录xxx里面添加Kconfig文件,并把Kconfig文件路径添加到**drivers/hdf_core/adapter/khdf/linux/Kconfig**里面: - ``` + ```c source "drivers/hdf/khdf/xxx/Kconfig" #目录为hdf模块软链接到kernel里面的目录 ``` - 添加模块目录到**drivers/adapter/khdf/linux/Makefile**: + 添加模块目录到**drivers/hdf_core/adapter/khdf/linux/Makefile**: - ``` + ```c obj-$(CONFIG_DRIVERS_HDF) += xxx/ ``` 在模块目录xxx里面添加Makefile文件,在Makefile文件里面添加模块代码编译规则: - ``` + ```c obj-y += xxx.o ``` @@ -189,7 +189,7 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 device0 :: deviceNode { // sample驱动的DeviceNode节点 policy = 1; // policy字段是驱动服务发布的策略,在驱动服务管理章节有详细介绍。 priority = 100; // 驱动启动优先级(0-200),值越大优先级越低,建议默认配100,优先级相同则不保证device的加载顺序。 - preload = 0; // 驱动按需加载字段,在本章节最后的说明有详细介绍。 + preload = 0; // 驱动按需加载字段。 permission = 0664; // 驱动创建设备节点权限 moduleName = "sample_driver"; // 驱动名称,该字段的值必须和驱动入口结构的moduleName值一致。 serviceName = "sample_service"; // 驱动对外发布服务的名称,必须唯一。 @@ -211,7 +211,9 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 > > - 进程的uid在文件**base/startup/init_lite/services/etc/passwd**中配置,进程的gid在文件**base/startup/init_lite/services/etc/group**中配置,进程uid和gid配置参考:[系统服务用户组添加方法](https://gitee.com/openharmony/startup_init_lite/wikis)。 > - > - caps值:比如业务模块要配置CAP_DAC_OVERRIDE,此处需要填写caps = ["DAC_OVERRIDE"],不能填写为caps = ["CAP_DAC_OVERRIDE"]。 + > - caps值:格式为caps = ["xxx"],如果要配置CAP_DAC_OVERRIDE,此处需要填写caps = ["DAC_OVERRIDE"],不能填写为caps = ["CAP_DAC_OVERRIDE"]。 + > + > - preload:驱动按需加载字段,参考[驱动加载](../driver/driver-hdf-load.md)。 - 驱动私有配置信息(可选) @@ -229,7 +231,7 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 } ``` - 配置信息定义之后,需要将该配置文件添加到板级配置入口文件hdf.hcs(这一块可以通过OpenHarmony驱动子系统在DevEco集成驱动开发套件工具一键式配置,具体使用方法参考驱动开发套件中的介绍),示例如下: + 配置信息定义之后,需要将该配置文件添加到板级配置入口文件hdf.hcs,示例如下: ``` @@ -237,27 +239,3 @@ HDF(Hardware Driver Foundation)框架以组件化的驱动模型作为核心 #include "sample/sample_config.hcs" ``` - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> 驱动加载方式支持按需加载和按序加载两种方式,具体使用方法如下: -> -> - 按需加载 -> -> ``` -> typedef enum { -> DEVICE_PRELOAD_ENABLE = 0, -> DEVICE_PRELOAD_ENABLE_STEP2, -> DEVICE_PRELOAD_DISABLE, -> DEVICE_PRELOAD_INVALID -> } DevicePreload; -> ``` -> -> - 配置文件中preload字段配成0(DEVICE_PRELOAD_ENABLE),则系统启动过程中默认加载。 -> -> - 配成1(DEVICE_PRELOAD_ENABLE_STEP2),当系统支持快启的时候,则在系统完成之后再加载这一类驱动,否则和DEVICE_PRELOAD_ENABLE含义相同。 -> -> - 配成2(DEVICE_PRELOAD_DISABLE),则系统启动过程中默认不加载,支持后续动态加载,当用户态获取驱动服务(参考[消息机制](../driver/driver-hdf-message-management.md))时,如果驱动服务不存在,HDF框架会尝试动态加载该驱动。 -> -> - 按序加载(需要驱动为默认加载) -> -> 配置文件中的priority(取值范围为整数0到200)是用来表示host和驱动的优先级。不同的host内的驱动,host的priority值越小,驱动加载优先级越高;同一个host内驱动的priority值越小,加载优先级越高。 diff --git a/zh-cn/device-dev/driver/driver-hdf-load.md b/zh-cn/device-dev/driver/driver-hdf-load.md new file mode 100644 index 0000000000000000000000000000000000000000..7ce200f248442dc6df054a5b70bee0c3ad612809 --- /dev/null +++ b/zh-cn/device-dev/driver/driver-hdf-load.md @@ -0,0 +1,30 @@ +# 驱动加载 + +## 驱动加载概述 + +HDF驱动框架提供把和配置的设备列表匹配成功的驱动程序加载起来的功能。 + +## 驱动加载策略 + +支持按需加载和按序加载两种策略,具体设备的加载策略由配置文件(参考[驱动开发](../driver/driver-hdf-development.md))中的preload字段来控制,配置值参考如下: + +```c +typedef enum { + DEVICE_PRELOAD_ENABLE = 0, + DEVICE_PRELOAD_ENABLE_STEP2 = 1, + DEVICE_PRELOAD_DISABLE = 2, + DEVICE_PRELOAD_INVALID +} DevicePreload; +``` + +### 按需加载 + +- preload字段配置为0(DEVICE_PRELOAD_ENABLE),则系统启动过程中默认加载。 + +- preload字段配置为1(DEVICE_PRELOAD_ENABLE_STEP2),当系统支持快速启动的时候,则在系统完成之后再加载这一类驱动,否则和DEVICE_PRELOAD_ENABLE含义相同。 + +- preload字段配置为2(DEVICE_PRELOAD_DISABLE),则系统启动过程中默认不加载,支持后续动态加载,当用户态获取驱动服务(参考[消息机制](../driver/driver-hdf-message-management.md))时,如果驱动服务不存在,HDF框架会尝试动态加载该驱动。 + +### 按序加载(默认加载策略) + +配置文件中的priority(取值范围为整数0到200)是用来表示host(驱动容器)和驱动的优先级。不同的host内的驱动,host的priority值越小,驱动加载优先级越高;同一个host内驱动的priority值越小,加载优先级越高。 diff --git a/zh-cn/device-dev/driver/driver-hdf-manage.md b/zh-cn/device-dev/driver/driver-hdf-manage.md index 483d60a3b6a0f89045e460803254aadde00c94a5..4dbf5da5f161e3102f6efb53adf0720d3b03e86c 100644 --- a/zh-cn/device-dev/driver/driver-hdf-manage.md +++ b/zh-cn/device-dev/driver/driver-hdf-manage.md @@ -57,7 +57,7 @@ HCS主要分为属性(Attribute)和节点(Node)两种结构。 - value的可用格式如下: - - 数字常量,支持二进制、八进制、十进制、十六进制数,具体参考数据类型节。 + - 数字常量,支持二进制、八进制、十进制、十六进制数,具体参考[数据类型](#数据类型)章节。 - 字符串,内容使用双引号("")引用。 - 节点引用。 @@ -83,7 +83,7 @@ HCS主要分为属性(Attribute)和节点(Node)两种结构。 - root节点中必须包含module属性,其值应该为一个字符串,用于表征该配置所属模块。 -- 节点中可以增加match_attr属性,其值为一个全局唯一的字符串。在解析配置时可以调用查找接口以该属性的值查找到包含该属性的节点。 +- 节点中可以增加match_attr属性,其值为一个全局唯一的字符串。当驱动程序在解析配置时可以以该属性的值为参数调用查找接口查找到包含该属性的节点。 ### 数据类型 @@ -97,7 +97,7 @@ HCS主要分为属性(Attribute)和节点(Node)两种结构。 - 八进制,0前缀,示例:0664。 -- 十进制 ,无前缀,且支持有符号与无符号,示例:1024,+1024均合法。负值在读取时注意使用有符号数读取接口。 +- 十进制 ,无前缀,且支持有符号与无符号,示例:1024,+1024均合法。驱动程序在读取负值时注意使用有符号数读取接口。 - 十六进制,0x前缀,示例:0xff00、0xFF。 diff --git a/zh-cn/device-dev/driver/driver-hdf-message-management.md b/zh-cn/device-dev/driver/driver-hdf-message-management.md index 27161c307123ea87643a25f1fafef216b77f989b..c277a3d302c388edd7bd1ce9a31ccb0c9ee9937f 100644 --- a/zh-cn/device-dev/driver/driver-hdf-message-management.md +++ b/zh-cn/device-dev/driver/driver-hdf-message-management.md @@ -39,19 +39,19 @@ 3. 在服务实现过程中,实现服务基类成员IDeviceIoService中的Dispatch方法。 - ``` + ```c // Dispatch是用来处理用户态发下来的消息 - int32_t SampleDriverDispatch(struct HdfDeviceObject *device, int cmdCode, struct HdfSBuf *data, struct HdfSBuf *reply) + int32_t SampleDriverDispatch(struct HdfDeviceIoClient *device, int cmdCode, struct HdfSBuf *data, struct HdfSBuf *reply) { - HDF_LOGE("sample driver lite A dispatch"); - return 0; + HDF_LOGI("sample driver lite A dispatch"); + return HDF_SUCCESS; } int32_t SampleDriverBind(struct HdfDeviceObject *device) { - HDF_LOGE("test for lite os sample driver A Open!"); + HDF_LOGI("test for lite os sample driver A Open!"); if (device == NULL) { HDF_LOGE("test for lite os sample driver A Open failed!"); - return -1; + return HDF_FAILURE; } static struct ISampleDriverService sampleDriverA = { .ioService.Dispatch = SampleDriverDispatch, @@ -59,36 +59,36 @@ .ServiceB = SampleDriverServiceB, }; device->service = (struct IDeviceIoService *)(&sampleDriverA); - return 0; + return HDF_SUCCESS; } ``` 4. 驱动定义消息处理函数中的cmd类型。 - ``` + ```c #define SAMPLE_WRITE_READ 1 // 读写操作码1 ``` 5. 用户态获取服务接口并发送消息到驱动。 - ``` + ```c int SendMsg(const char *testMsg) { if (testMsg == NULL) { HDF_LOGE("test msg is null"); - return -1; + return HDF_FAILURE; } struct HdfIoService *serv = HdfIoServiceBind("sample_driver"); if (serv == NULL) { HDF_LOGE("fail to get service"); - return -1; + return HDF_FAILURE; } - struct HdfSBuf *data = HdfSBufObtainDefaultSize(); + struct HdfSBuf *data = HdfSbufObtainDefaultSize(); if (data == NULL) { HDF_LOGE("fail to obtain sbuf data"); - return -1; + return HDF_FAILURE; } - struct HdfSBuf *reply = HdfSBufObtainDefaultSize(); + struct HdfSBuf *reply = HdfSbufObtainDefaultSize(); if (reply == NULL) { HDF_LOGE("fail to obtain sbuf reply"); ret = HDF_DEV_ERR_NO_MEMORY; @@ -105,8 +105,8 @@ goto out; } out: - HdfSBufRecycle(data); - HdfSBufRecycle(reply); + HdfSbufRecycle(data); + HdfSbbufRecycle(reply); HdfIoServiceRecycle(serv); return ret; } @@ -115,31 +115,31 @@ 6. 用户态接收该驱动上报的消息。 1. 用户态编写驱动上报消息的处理函数。 - ``` + ```c static int OnDevEventReceived(void *priv, uint32_t id, struct HdfSBuf *data) { OsalTimespec time; OsalGetTime(&time); - HDF_LOGE("%s received event at %llu.%llu", (char *)priv, time.sec, time.usec); + HDF_LOGI("%{public}s received event at %{public}llu.%{public}llu", (char *)priv, time.sec, time.usec); const char *string = HdfSbufReadString(data); if (string == NULL) { HDF_LOGE("fail to read string in event data"); - return -1; + return HDF_FAILURE; } - HDF_LOGE("%s: dev event received: %d %s", (char *)priv, id, string); - return 0; + HDF_LOGI("%{public}s: dev event received: %{public}d %{public}s", (char *)priv, id, string); + return HDF_SUCCESS; } ``` 2. 用户态注册接收驱动上报消息的操作方法。 - ``` + ```c int RegisterListen() { struct HdfIoService *serv = HdfIoServiceBind("sample_driver"); if (serv == NULL) { HDF_LOGE("fail to get service"); - return -1; + return HDF_FAILURE; } static struct HdfDevEventlistener listener = { .callBack = OnDevEventReceived, @@ -147,20 +147,20 @@ }; if (HdfDeviceRegisterEventListener(serv, &listener) != 0) { HDF_LOGE("fail to register event listener"); - return -1; + return HDF_FAILURE; } ...... HdfDeviceUnregisterEventListener(serv, &listener); HdfIoServiceRecycle(serv); - return 0; + return HDF_SUCCESS; } ``` 3. 驱动上报事件。 - ``` - int32_t SampleDriverDispatch(struct HdfDeviceObject *device, int cmdCode, struct HdfSBuf *data, struct HdfSBuf *reply) + ```c + int32_t SampleDriverDispatch(HdfDeviceIoClient *client, int cmdCode, struct HdfSBuf *data, struct HdfSBuf *reply) { ... // process api call here - return HdfDeviceSendEvent(deviceObject, cmdCode, data); + return HdfDeviceSendEvent(client->device, cmdCode, data); } ``` diff --git a/zh-cn/device-dev/driver/driver-hdf-overview.md b/zh-cn/device-dev/driver/driver-hdf-overview.md index c5f99925f10b8992392e85d7e5a6ad0e1832b586..6d9eda2b1cfdcc8d65b8dadc9d978454771592dc 100755 --- a/zh-cn/device-dev/driver/driver-hdf-overview.md +++ b/zh-cn/device-dev/driver/driver-hdf-overview.md @@ -3,7 +3,7 @@ ## 简介 -HDF(Hardware Driver Foundation)驱动框架,为驱动开发者提供驱动框架能力,包括驱动加载、驱动服务管理和驱动消息机制。旨在构建统一的驱动架构平台,为驱动开发者提供更精准、更高效的开发环境,力求做到一次开发,多系统部署。 +HDF(Hardware Driver Foundation)驱动框架,为驱动开发者提供驱动框架能力,包括驱动加载、驱动服务管理、驱动消息机制和配置管理。旨在构建统一的驱动架构平台,为驱动开发者提供更精准、更高效的开发环境,力求做到一次开发,多系统部署。 ## 驱动加载 @@ -27,3 +27,8 @@ HDF框架可以集中管理驱动服务,开发者可直接通过HDF框架对 ## 驱动消息机制 HDF框架提供统一的驱动消息机制,支持用户态应用向内核态驱动发送消息,也支持内核态驱动向用户态应用发送消息。 + + +## 配置管理 + +HCS(HDF Configuration Source)是HDF驱动框架的配置描述源码,内容以Key-Value为主要形式。它实现了配置代码与驱动代码解耦,便于开发者进行配置管理。 \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-hdf-sample.md b/zh-cn/device-dev/driver/driver-hdf-sample.md index 1ae83ff0e1e231063b2552546c8162ebdafcb5c2..29dce6e3df1ca440ebc01b5c843c65f56bd85a81 100644 --- a/zh-cn/device-dev/driver/driver-hdf-sample.md +++ b/zh-cn/device-dev/driver/driver-hdf-sample.md @@ -51,7 +51,7 @@ root { 基于HDF框架编写的sample驱动代码如下(编译参考[驱动开发](../driver/driver-hdf-development.md)): -``` +```c #include #include #include @@ -59,34 +59,34 @@ root { #include "hdf_base.h" #include "hdf_device_desc.h" -#define HDF_LOG_TAG "sample_driver" +#define HDF_LOG_TAG sample_driver #define SAMPLE_WRITE_READ 123 -int32_t HdfSampleDriverDispatch( - struct HdfDeviceObject *deviceObject, int id, struct HdfSBuf *data, struct HdfSBuf *reply) +static int32_t HdfSampleDriverDispatch( + struct HdfDeviceIoClient *client, int id, struct HdfSBuf *data, struct HdfSBuf *reply) { - HDF_LOGE("%s: received cmd %d", __func__, id); + HDF_LOGI("%{public}s: received cmd %{public}d", __func__, id); if (id == SAMPLE_WRITE_READ) { const char *readData = HdfSbufReadString(data); if (readData != NULL) { - HDF_LOGE("%s: read data is: %s", __func__, readData); + HDF_LOGE("%{public}s: read data is: %{public}s", __func__, readData); } if (!HdfSbufWriteInt32(reply, INT32_MAX)) { - HDF_LOGE("%s: reply int32 fail", __func__); + HDF_LOGE("%{public}s: reply int32 fail", __func__); } - return HdfDeviceSendEvent(deviceObject, id, data); + return HdfDeviceSendEvent(client->device, id, data); } return HDF_FAILURE; } -void HdfSampleDriverRelease(struct HdfDeviceObject *deviceObject) +static void HdfSampleDriverRelease(struct HdfDeviceObject *deviceObject) { // release resources here return; } -int HdfSampleDriverBind(struct HdfDeviceObject *deviceObject) +static int HdfSampleDriverBind(struct HdfDeviceObject *deviceObject) { if (deviceObject == NULL) { return HDF_FAILURE; @@ -98,17 +98,17 @@ int HdfSampleDriverBind(struct HdfDeviceObject *deviceObject) return HDF_SUCCESS; } -int HdfSampleDriverInit(struct HdfDeviceObject *deviceObject) +static int HdfSampleDriverInit(struct HdfDeviceObject *deviceObject) { if (deviceObject == NULL) { - HDF_LOGE("%s::ptr is null!", __func__); + HDF_LOGE("%{public}s::ptr is null!", __func__); return HDF_FAILURE; } - HDF_LOGE("Sample driver Init success"); + HDF_LOGI("Sample driver Init success"); return HDF_SUCCESS; } -struct HdfDriverEntry g_sampleDriverEntry = { +static struct HdfDriverEntry g_sampleDriverEntry = { .moduleVersion = 1, .moduleName = "sample_driver", .Bind = HdfSampleDriverBind, @@ -122,10 +122,10 @@ HDF_INIT(g_sampleDriverEntry); ## 编写用户程序和驱动交互代码 -基于HDF框架编写的用户态程序和驱动交互的代码如下(代码可以放在目录drivers/adapter/uhdf下面编译,build.gn可以参考drivers/framework/sample/platform/uart/dev/build.gn): +基于HDF框架编写的用户态程序和驱动交互的代码如下(代码可以放在目录drivers/hdf_core/adapter/uhdf下面编译,BUILD.gn可以参考drivers/hdf_core/framework/sample/platform/uart/dev/BUILD.gn): -``` +```c #include #include #include @@ -134,7 +134,7 @@ HDF_INIT(g_sampleDriverEntry); #include "hdf_sbuf.h" #include "hdf_io_service_if.h" -#define HDF_LOG_TAG "sample_test" +#define HDF_LOG_TAG sample_test #define SAMPLE_SERVICE_NAME "sample_service" #define SAMPLE_WRITE_READ 123 @@ -149,7 +149,7 @@ static int OnDevEventReceived(void *priv, uint32_t id, struct HdfSBuf *data) g_replyFlag = 1; return HDF_FAILURE; } - HDF_LOGE("%s: dev event received: %u %s", (char *)priv, id, string); + HDF_LOGI("%{public}s: dev event received: %{public}u %{public}s", (char *)priv, id, string); g_replyFlag = 1; return HDF_SUCCESS; } @@ -157,13 +157,13 @@ static int OnDevEventReceived(void *priv, uint32_t id, struct HdfSBuf *data) static int SendEvent(struct HdfIoService *serv, char *eventData) { int ret = 0; - struct HdfSBuf *data = HdfSBufObtainDefaultSize(); + struct HdfSBuf *data = HdfSbufObtainDefaultSize(); if (data == NULL) { HDF_LOGE("fail to obtain sbuf data"); return 1; } - struct HdfSBuf *reply = HdfSBufObtainDefaultSize(); + struct HdfSBuf *reply = HdfSbufObtainDefaultSize(); if (reply == NULL) { HDF_LOGE("fail to obtain sbuf reply"); ret = HDF_DEV_ERR_NO_MEMORY; @@ -188,10 +188,10 @@ static int SendEvent(struct HdfIoService *serv, char *eventData) ret = HDF_ERR_INVALID_OBJECT; goto out; } - HDF_LOGE("Get reply is: %d", replyData); + HDF_LOGI("Get reply is: %{public}d", replyData); out: - HdfSBufRecycle(data); - HdfSBufRecycle(reply); + HdfSbufRecycle(data); + HdfSbufRecycle(reply); return ret; } @@ -237,8 +237,8 @@ int main() > > deps = [ > -> "//drivers/adapter/uhdf/manager:hdf_core", +> "//drivers/hdf_core/adapter/uhdf/manager:hdf_core", > -> "//drivers/adapter/uhdf/posix:hdf_posix_osal", +> "//drivers/hdf_core/adapter/uhdf/posix:hdf_posix_osal", > > ] diff --git a/zh-cn/device-dev/driver/driver-hdf-servicemanage.md b/zh-cn/device-dev/driver/driver-hdf-servicemanage.md index 37f57ad77dbd05f9e2aaea70096b408c012eb57e..fd2e911c51e34a27990fcac9c19c4b5081c809d4 100755 --- a/zh-cn/device-dev/driver/driver-hdf-servicemanage.md +++ b/zh-cn/device-dev/driver/driver-hdf-servicemanage.md @@ -8,7 +8,7 @@ HDF框架定义了驱动对外发布服务的策略,由配置文件中的polic -``` +```c typedef enum { /* 驱动不提供服务 */ SERVICE_POLICY_NONE = 0, @@ -28,7 +28,7 @@ typedef enum { ## 使用场景 -当驱动以接口的形式对外提供能力时,可以使用HDF框架的驱动服务管理能力。 +当驱动需要以接口的形式对外提供能力时,可以使用HDF框架的驱动服务管理能力。 ## 接口说明 @@ -50,7 +50,7 @@ typedef enum { 1. 驱动服务编写。 - ``` + ```c // 驱动服务结构的定义 struct ISampleDriverService { struct IDeviceIoService ioService; // 服务结构的首个成员必须是IDeviceIoService类型的成员。 @@ -62,66 +62,69 @@ typedef enum { int32_t SampleDriverServiceA(void) { // 驱动开发者实现业务逻辑 - return 0; + return HDF_SUCCESS; } int32_t SampleDriverServiceB(uint32_t inputCode) { // 驱动开发者实现业务逻辑 - return 0; + return HDF_SUCCESS; } ``` -2. 驱动服务绑定到HDF框架中,实现HdfDriverEntry中的Bind指针函数。 +2. 驱动服务绑定。 + + 开发者实现HdfDriverEntry中的Bind指针函数,如下的SampleDriverBind,把驱动服务绑定到HDF框架中。 - ``` + ```c int32_t SampleDriverBind(struct HdfDeviceObject *deviceObject) { // deviceObject为HDF框架给每一个驱动创建的设备对象,用来保存设备相关的私有数据和服务接口。 if (deviceObject == NULL) { HDF_LOGE("Sample device object is null!"); - return -1; + return HDF_FAILURE; } static struct ISampleDriverService sampleDriverA = { .ServiceA = SampleDriverServiceA, .ServiceB = SampleDriverServiceB, }; deviceObject->service = &sampleDriverA.ioService; - return 0; + return HDF_SUCCESS; } ``` 3. 驱动服务获取。 - 驱动服务的获取有两种方式,HDF框架提供接口直接获取和订阅机制获取。 + + 应用程序开发者获取驱动服务有两种方式:通过HDF接口直接获取和通过HDF提供的订阅机制获取。 - 通过HDF接口直接获取 - 当明确驱动已经加载完成时,获取该驱动的服务可以通过HDF框架提供的能力接口直接获取,如下所示: + 当驱动服务获取者明确驱动已经加载完成时,获取该驱动的服务可以通过HDF框架提供的能力接口直接获取,如下所示: - ``` + ```c const struct ISampleDriverService *sampleService = (const struct ISampleDriverService *)DevSvcManagerClntGetService("sample_driver"); if (sampleService == NULL) { - return -1; + return HDF_FAILURE; } sampleService->ServiceA(); sampleService->ServiceB(5); ``` - 通过HDF提供的订阅机制获取 - 当内核态对驱动(同一个host)加载的时机不感知时,可以通过HDF框架提供的订阅机制来订阅该驱动。当该驱动加载完成时,HDF框架会将被订阅的驱动服务发布给订阅者,实现方式如下所示: + 当内核态驱动服务获取者对驱动(同一个host)加载的时机不感知时,可以通过HDF框架提供的订阅机制来订阅该驱动服务。当该驱动加载完成时,HDF框架会将被订阅的驱动服务发布给订阅者(驱动服务获取者),实现方式如下所示: - ``` - // 订阅回调函数的编写,当被订阅的驱动加载完成后,HDF框架会将被订阅驱动的服务发布给订阅者,通过这个回调函数给订阅者使用 - // object为订阅者的私有数据,service为被订阅的服务对象 + ```c + // 订阅回调函数的编写,当被订阅的驱动加载完成后,HDF框架会将被订阅驱动的服务发布给订阅者,通过这个回调函数给订阅者使用。 + // object为订阅者的私有数据,service为被订阅的服务对象。 int32_t TestDriverSubCallBack(struct HdfDeviceObject *deviceObject, const struct HdfObject *service) { const struct ISampleDriverService *sampleService = (const struct ISampleDriverService *)service; if (sampleService == NULL) { - return -1; + return HDF_FAILURE; } sampleService->ServiceA(); sampleService->ServiceB(5); @@ -131,13 +134,13 @@ typedef enum { { if (deviceObject == NULL) { HDF_LOGE("Test driver init failed, deviceObject is null!"); - return -1; + return HDF_FAILURE; } struct SubscriberCallback callBack; callBack.deviceObject = deviceObject; callBack.OnServiceConnected = TestDriverSubCallBack; int32_t ret = HdfDeviceSubscribeService(deviceObject, "sample_driver", callBack); - if (ret != 0) { + if (ret != HDF_SUCCESS) { HDF_LOGE("Test driver subscribe sample driver failed!"); } return ret; diff --git a/zh-cn/device-dev/driver/driver-peripherals-light-des.md b/zh-cn/device-dev/driver/driver-peripherals-light-des.md index 3fe251ccb9d9c25668aa97a8c58792947803e285..38df75af2d9e44c85a6f2e6dda5c533e93c8d6c2 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-light-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-light-des.md @@ -19,14 +19,14 @@ Light驱动模型为上层Light硬件服务层提供稳定的灯控制能力接 ![Light驱动运行图](figures/Light驱动运行图.png) -Light驱动模型以标准系统Hi3516DV300为例,介绍整个驱动加载及运行流程: +以标准系统Hi3516DV300为例,介绍Light模块驱动加载及运行流程: -1. 从device_info.hcs配置文件的Light Host里读取Light设备管理配置信息。 -2. 从light_config.hcs配置文件读取Light数据配置信息。 -3. 解析Light设备管理配置信息,并关联对应设备驱动。 -4. 客户端下发Light Stub控制到服务端。 -5. 服务端调用Light Stub控制。 -6. 启动Light抽象驱动接口。 +1. Device Manager从device_info.hcs配置文件中读取Light设备管理配置信息。 +2. Device Manager从light_config.hcs配置文件中读取Light数据配置信息。 +3. HCS Parser解析Light设备管理配置信息,加载对应的Light Host,并控制Host完成驱动的加载。 +4. Light Proxy获取到Light HDI接口服务实例后,通过IPC(Inter-Process Communication)调用到Light Stub。 +5. Light Stub主要处理与IPC相关的业务逻辑,完成参数反序列化后调用Light Controller。 +6. Light Controller中是HDI接口的真正实现,通过IPC调用Light抽象驱动接口,进一步操作Light硬件设备。 ## 开发指导 @@ -36,33 +36,32 @@ Light驱动模型以标准系统Hi3516DV300为例,介绍整个驱动加载及 ### 接口说明 -Light驱动模型支持获取系统中所有灯的信息,动态配置闪烁模式和闪烁时间的能力。Light Hardware服务调用GetLightInfo获取Light设备的基本信息;调用TurnOnLight接口启动配置的闪烁效果。Light驱动模型对外开放的API接口能力,参考表1。 +Light驱动模型支持获取系统中所有灯的信息、动态配置闪烁模式和闪烁时间的能力。Light硬件服务调用GetLightInfo获取Light设备的基本信息,调用TurnOnLight接口启动配置的闪烁效果,调用TurnOffLight接口关闭Light设备。Light驱动模型对外开放的API接口能力,参考表1。 **表1** Light驱动模型对外API接口能力介绍 | 接口名 | 功能描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| int32_t (*GetLightInfo)(struct LightInfo **lightInfo, uint32_t *count) | 获取系统中所有灯的信息,lightInfo表示灯设备的基本信息,count表示获取灯的个数。 | -| int32_t (*TurnOnLight)(uint32_t lightId, struct LightEffect *effect) | 根据指定的灯类型打开灯列表中可用的灯,lightId表示灯类型,effect表示要设置的效果信息。 | -| int32_t (*TurnOffLight)(uint32_t lightId) | 根据指定的灯类型关闭灯列表中可用的灯。 | +| GetLightInfo([out] struct HdfLightInfo[] info) | 获取当前系统中所有类型的灯信息,info表示指向灯信息的二级指针。 | +| TurnOnLight([in] int lightId, [in] struct HdfLightEffect effect) | 根据指定的灯类型ID打开列表中的可用灯,lightId表示灯类型,effect表示指向灯效果的指针。 | +| TurnOffLight([in] int lightId) | 根据指定的灯类型ID关闭列表中的可用灯。 | ### 开发步骤 -1. 基于HDF驱动框架,按照驱动Driver Entry程序,完成Light抽象驱动开发(主要由Bind、Init、Release、Dispatch函数接口实现),资源配置及HCS配置文件解析。完成Light驱动的设备信息配置。 +1. 基于HDF驱动框架,按照驱动Driver Entry程序,完成Light抽象驱动开发(主要由Bind、Init、Release、Dispatch函数接口实现),资源配置及HCS配置文件解析。 - 调用HDF_INIT将驱动入口注册到HDF框架中。在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - Light驱动模型使用HCS配置文件作为配置描述源码。HCS配置字段详细介绍请参考[配置管理](driver-hdf-manage.md)。 - 其Driver Entry入口函数定义如下: + - Light驱动模型使用HCS配置文件作为配置描述源码。HCS配置字段详细介绍请参考[配置管理](driver-hdf-manage.md)。其Driver Entry入口函数定义如下: ```c /* 注册灯入口数据结构体对象 */ struct HdfDriverEntry g_lightDriverEntry = { - .moduleVersion = 1, // 灯模块版本号 - .moduleName = "HDF_LIGHT", // 灯模块名,要与device_info.hcs文件里灯moduleName字段值一样 - .Bind = BindLightDriver, // 灯绑定函数 - .Init = InitLightDriver, // 灯初始化函数 + .moduleVersion = 1, // 灯模块版本号 + .moduleName = "HDF_LIGHT", // 灯模块名,要与device_info.hcs文件里灯moduleName字段值一样 + .Bind = BindLightDriver, // 灯绑定函数 + .Init = InitLightDriver, // 灯初始化函数 .Release = ReleaseLightDriver, // 灯资源释放函数 }; - /* 调用HDF_INIT将驱动入口注册到HDF框架中。在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release函数释放驱动资源并退出 */ + /* 调用HDF_INIT将驱动入口注册到HDF框架中 */ HDF_INIT(g_lightDriverEntry); ``` @@ -120,7 +119,7 @@ Light驱动模型支持获取系统中所有灯的信息,动态配置闪烁模 } /* 工作项初始化 */ if (HdfWorkInit(&drvData->work, LightWorkEntry, (void*)drvData) != HDF_SUCCESS) { - HDF_LOGE("%s: init workQueue fail!", __func__); + HDF_LOGE("%s: init work fail!", __func__); return HDF_FAILURE; } /* 解析HCS配置文件 */ @@ -158,30 +157,34 @@ Light驱动模型支持获取系统中所有灯的信息,动态配置闪烁模 } ``` - - Light设备管理模块负责系统中Light器件接口发布。在系统启动过程中,HDF框架机制通过Light Host里设备HCS配置信息,加载设备管理驱动。 + - Light设备管理模块负责系统中Light器件接口发布。在系统启动过程中,HDF框架机制通过Light Host里的设备HCS配置信息,加载设备管理驱动。 - ``` + ```c /* Light设备HCS配置 */ - device_light :: device { - device0 :: deviceNode { - policy = 2; // 驱动服务发布的策略(0:不提供服务,1:对内核态发布服务;2:对内核态和用户态都发布服务) - priority = 100; // Light驱动启动优先级(0-200),值越大优先级越低,建议配置为100,优先级相同则不保证device的加载顺序 - preload = 0; // 驱动按需加载字段,0:加载;2:不加载 - permission = 0664; // 驱动创建设备节点权限 - moduleName = "HDF_LIGHT"; // Light驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 - serviceName = "hdf_light"; // Light驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "hdf_light_driver"; // 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值相等 + light :: host { + hostName = "light_host"; + device_light :: device { + device0 :: deviceNode { + policy = 2; // 驱动服务发布的策略(0:不提供服务,1:对内核态发布服务;2:对内核态和用户态都发布服务) + priority = 100; // Light驱动启动优先级(0-200),值越大优先级越低,建议配置为100,优先级相同则不保证device的加载顺序 + preload = 0; // 驱动按需加载字段,0:加载;2:不加载 + permission = 0664; // 驱动创建设备节点权限 + moduleName = "HDF_LIGHT"; // Light驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 + serviceName = "hdf_light"; // Light驱动对外发布服务的名称,必须唯一 + deviceMatchAttr = "hdf_light_driver"; // 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值相等 + } } + } ``` -2. 调用配置解析接口,完成器件属性信息解析,器件寄存器解析,并注册到Light设备管理中。 +2. 调用配置解析接口,完成器件属性信息解析、器件寄存器解析,并注册到Light设备管理中。 ```c /* 分配资源,解析灯HCS配置。 */ static int32_t ParseLightInfo(const struct DeviceResourceNode *node, const struct DeviceResourceIface *parser) { ..... - /* 从HCS配置获取支持灯的类型个数 */ + /* 从HCS配置获取支持的灯类型个数 */ drvData->lightNum = parser->GetElemNum(light, "lightId"); .... for (i = 0; i < drvData->lightNum; ++i) { @@ -191,38 +194,39 @@ Light驱动模型支持获取系统中所有灯的信息,动态配置闪烁模 } for (i = 0; i < drvData->lightNum; ++i) { - ..... - /* 类型作为下标开辟空间 */ - drvData->info[temp] = (struct LightDeviceInfo *)OsalMemCalloc(sizeof(struct LightDeviceInfo)); - ..... - /* 将Light设备信息进行填充 */ - ret = parser->GetUint32(node, "busRNum", (uint32_t *)&drvData->info[temp]->busRNum, 0); - if (ret != HDF_SUCCESS) { - /* 如果没有成功获取busNum,代表不支持设置busNum对应颜色的灯。 */ - drvData->info[temp]->busRNum = LIGHT_INVALID_GPIO; - } - ret = parser->GetUint32(node, "busGNum", (uint32_t *)&drvData->info[temp]->busGNum, 0); - if (ret != HDF_SUCCESS) { - drvData->info[temp]->busGNum = LIGHT_INVALID_GPIO; - } - ret = parser->GetUint32(node, "busBNum", (uint32_t *)&drvData->info[temp]->busBNum, 0); - if (ret != HDF_SUCCESS) { - drvData->info[temp]->busBNum = LIGHT_INVALID_GPIO; + ..... + /* 类型作为下标开辟空间 */ + drvData->info[temp] = (struct LightDeviceInfo *)OsalMemCalloc(sizeof(struct LightDeviceInfo)); + ..... + /* 将Light设备信息进行填充 */ + ret = parser->GetUint32(node, "busRNum", (uint32_t *)&drvData->info[temp]->busRNum, 0); + if (ret != HDF_SUCCESS) { + /* 如果没有成功获取busNum,代表不支持设置busNum对应颜色的灯。 */ + drvData->info[temp]->busRNum = LIGHT_INVALID_GPIO; + } + ret = parser->GetUint32(node, "busGNum", (uint32_t *)&drvData->info[temp]->busGNum, 0); + if (ret != HDF_SUCCESS) { + drvData->info[temp]->busGNum = LIGHT_INVALID_GPIO; + } + ret = parser->GetUint32(node, "busBNum", (uint32_t *)&drvData->info[temp]->busBNum, 0); + if (ret != HDF_SUCCESS) { + drvData->info[temp]->busBNum = LIGHT_INVALID_GPIO; + } } ..... return HDF_SUCCESS; } ``` -3. 完成Light获取类型、闪烁和停止接口开发,会根据闪烁模式创建和销毁定时器。 +3. 完成Light类型获取、闪烁模式设置和停止的接口开发,并实现根据闪烁模式创建和销毁定时器。 ```c - /* Light驱动服务调用GetAllLightInfo获取灯类型,TurnOnLight接口启动闪烁模式, + /* Light驱动服务调用GetAllLightInfo接口获取灯类型,调用TurnOnLight接口启动闪烁模式, 调用TurnOffLight接口停止闪烁。 */ static int32_t GetAllLightInfo(struct HdfSBuf *data, struct HdfSBuf *reply) { ..... - /* 获取灯的类型个数 */ + /* 获取灯类型的个数 */ if (!HdfSbufWriteUint32(reply, drvData->lightNum)) { HDF_LOGE("%s: write sbuf fail", __func__); return HDF_FAILURE; @@ -302,13 +306,13 @@ Light驱动模型支持获取系统中所有灯的信息,动态配置闪烁模 /* 创建定时器 */ if (OsalTimerCreate(&drvData->timer, drvData->info[lightId]->onTime, LightTimerEntry, (uintptr_t)lightId) != HDF_SUCCESS) { - HDF_LOGE("%s: create light timer fail!", __func__); - return HDF_FAILURE; + HDF_LOGE("%s: create light timer fail!", __func__); + return HDF_FAILURE; } /* 启动周期定时器 */ if (OsalTimerStartLoop(&drvData->timer) != HDF_SUCCESS) { - HDF_LOGE("%s: start light timer fail!", __func__); - return HDF_FAILURE; + HDF_LOGE("%s: start light timer fail!", __func__); + return HDF_FAILURE; } } return HDF_SUCCESS; @@ -427,4 +431,3 @@ HWTEST_F(HdfLightTest, EnableLight002, TestSize.Level1) } } ``` - diff --git a/zh-cn/device-dev/driver/driver-peripherals-vibrator-des.md b/zh-cn/device-dev/driver/driver-peripherals-vibrator-des.md index af09963c38ba1d415c4529b0610e16894276d016..2a29f1c617ebabd01867877fabdda4c23c899a30 100755 --- a/zh-cn/device-dev/driver/driver-peripherals-vibrator-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-vibrator-des.md @@ -4,7 +4,7 @@ ### 功能简介 -为了快速开发传感器驱动,基于HDF(Hardware Driver Foundation)驱动框架开发了马达(Vibrator)驱动模型。马达驱动模型,屏蔽设备驱动与系统交互的实现,为硬件服务层提供统一稳定的驱动接口能力,为驱动开发者提供开放的接口和解析接口的能力,用于不同操作系统马达设备部件的部署指导和马达设备部件驱动的开发。马达驱动模型如图1所示: +为了快速开发马达驱动,基于HDF(Hardware Driver Foundation)驱动框架开发了马达(Vibrator)驱动模型。马达驱动模型,屏蔽设备驱动与系统交互的实现,为硬件服务层提供统一稳定的驱动接口能力,为驱动开发者提供开放的接口和解析接口的能力,用于不同操作系统马达设备部件的部署指导和马达设备部件驱动的开发。马达驱动模型如图1所示: **图 1** 马达驱动模型图 @@ -12,7 +12,17 @@ ### 基本概念 -系统通过调用马达实现对设备的振动控制。目前,马达只有两种振动方式: +根据振动原理的不同,目前马达可以分为两种: + +- 转子马达 + + 转子马达依靠旋转带动配重振动,分为普通转子和币型转子两种。转子马达的启停反应慢,并且无法实现多种振动模式,但其优点是成本低且体积小。 + +- 线性马达 + + 线性马达依靠磁力快速抖动配重来振动,分为纵向线性马达和横向线性马达两种。线性马达的启停都非常快,可以实现不同振感且具有良好的方向性。 + +系统通过调用马达驱动接口实现对设备的振动控制。目前,马达只有两种振动方式: - 单次振动 @@ -20,7 +30,7 @@ - 周期振动 - 周期振动是指按照预置的效果模式控制振动。例如:预置效果为“haptic.clock.timer” = [600, 600, 200, 600],等待600ms,振动600ms,等待200ms,振动600ms。 + 周期振动是指按照预置的效果模式控制振动。例如:预置效果为“haptic.clock.timer” = [600, 600, 200, 600],表示等待600ms,振动600ms,等待200ms,振动600ms。 ### 运作机制 @@ -30,18 +40,18 @@ ![Vibrator驱动运行图](figures/Vibrator驱动运行图.png) -马达驱动模型以标准系统Hi3516DV300产品为例,介绍整个驱动加载及运行流程: +以标准系统Hi3516DV300产品为例,介绍马达模块驱动加载及运行流程: -1. 从device_info.hcs配置文件中的Vibrator Host读取Vibrator管理配置信息。 -2. 解析Vibrator管理配置信息,并关联对应马达抽象驱动。 -3. 从linear_vibrator_config.hcs配置文件中读取Vibrator数据配置信息。 -4. 解析Vibrator数据配置信息,并关联对应Haptic驱动。 -5. 客户端下发Vibrator Stub控制到服务端。 -6. Vibrator Stub控制调用马达服务。 -7. 初始化马达抽象驱动接口。 -8. Haptic中起线程,解析效果模块。 -9. Haptic调用马达抽象驱动中的Start接口。 -10. 马达抽象驱动调用马达差异化驱动中的Start接口。 +1. Device Manager从device_info.hcs配置文件中读取Vibrator管理配置信息。 +2. HCS Parser解析Vibrator管理配置信息,并加载对应的马达抽象驱动。 +3. Device Manager从linear_vibrator_config.hcs配置文件中读取Vibrator数据配置信息。 +4. HCS Parser解析Vibrator数据配置信息,并加载对应的Haptic驱动。 +5. Vibrator Proxy获取到Vibrator HDI接口服务实例后,通过IPC(Inter-Process Communication)调用到Vibrator Stub。 +6. Vibrator Stub主要处理与IPC相关的业务逻辑,完成参数反序列化后调用Vibrator Controller。 +7. Vibrator Controller中是HDI接口的真正实现,通过IPC调用Vibrator抽象驱动接口。 +8. 在Haptic驱动中起线程,解析效果模块。 +9. Haptic驱动调用马达抽象驱动中的Start接口。 +10. 马达抽象驱动进一步调用马达差异化驱动中的Start接口,控制马达设备以给定的效果振动。 ## 开发指导 @@ -51,36 +61,36 @@ ### 接口说明 -马达驱动模型支持静态HCS配置和动态参数两种振动效果配置能力。马达硬件服务调用StartOnce接口动态配置持续振动;调用Start接口启动静态配置的振动效果。马达驱动模型对HDI开放的API接口能力,如下表所示。 +马达驱动模型支持静态HCS配置和动态参数两种振动效果配置能力。马达硬件服务调用StartOnce接口动态配置持续振动,调用Start接口启动静态配置的振动效果。马达驱动模型对HDI开放的API接口能力,如下表所示。 **表 1** 马达驱动模型对外API接口能力介绍 | 接口名 | 功能描述 | | -------------------------------------- | ------------------------------------------------ | -| int32_t StartOnce(uint32_t duration) | 按照指定持续时间触发振动马达,duration为振动持续时长。 | -| int32_t Start(const char *effectType) | 按照指定预置效果启动马达,effectType表示预置的预置效果。 | -| int32_t Stop(enum VibratorMode mode) | 按照指定的振动模式停止马达振动。 | -| int32_t EnableVibratorModulation(uint32_t duration, int32_t intensity, int32_t frequency) | 按照指定振幅、频率、持续时间触发振动马达。duration为振动持续时长,intensity为振动强度,frequency为振动频率。 | -| int32_t GetVibratorInfo(struct VibratorInfo **vibratorInfo); | 获取马达信息,包括是否支持振幅和频率的设置及振幅和频率的设置范围 。 | +| StartOnce([in] unsigned int duration) | 控制马达以执行给定持续时间的单次振动,duration表示单次振动的持续时间。 | +| Start([in] String effectType) | 控制马达以预置效果执行周期性振动,effectType表示马达振动的预设效果类型。 | +| Stop([in] enum HdfVibratorMode mode) | 停止马达振动,mode表示振动模式,可以是单次或周期性的。 | +| EnableVibratorModulation([in] unsigned int duration, [in] int intensity, [in] int frequency) | 根据传入的振动效果启动马达,duration表示马达振动的持续时间,intensity表示振动周期内的马达振幅,frequency表示振动周期内的马达频率。 | +| GetVibratorInfo([out] struct HdfVibratorInfo[] vibratorInfo) | 获取系统中支持设置振幅和频率的所有马达信息,vibratorInfo表示指向马达信息的指针。 | ### 开发步骤 Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能力接口,包括马达一次振动、马达效果配置震动、马达停止。基于HDF驱动框架开发的马达驱动模型,实现跨操作系统迁移、器件差异配置等功能。具体的开发步骤如下: -1. 基于HDF驱动框架,按照驱动Driver Entry程序,完成马达抽象驱动开发,主要由Bind、Init、Release、Dispatch函数接口实现,配置资源和HCS解析。 +1. 基于HDF驱动框架,按照驱动Driver Entry程序,完成马达抽象驱动开发(主要由Bind、Init、Release、Dispatch函数接口实现),配置资源和HCS解析。 - - 调用HDF_INIT将驱动入口注册到HDF框架中,在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出马达驱动模型,使用HCS作为配置描述源码。HCS配置字段详细介绍参考[配置管理](driver-hdf-manage.md)。其中Driver Entry入口函数定义如下: + - 调用HDF_INIT将驱动入口注册到HDF框架中。在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出马达驱动模型,使用HCS作为配置描述源码。HCS配置字段详细介绍参考[配置管理](driver-hdf-manage.md)。其中Driver Entry入口函数定义如下: ```c /* 注册马达抽象驱动入口数据结构体对象 */ struct HdfDriverEntry g_vibratorDriverEntry = { - .moduleVersion = 1, // 马达模块版本号 - .moduleName = "HDF_VIBRATOR", // 马达模块名,要与device_info.hcs文件里的马达moduleName字段值一样 - .Bind = BindVibratorDriver, // 马达绑定函数 - .Init = InitVibratorDriver, // 马达初始化函数 + .moduleVersion = 1, // 马达模块版本号 + .moduleName = "HDF_VIBRATOR", // 马达模块名,要与device_info.hcs文件里的马达moduleName字段值一样 + .Bind = BindVibratorDriver, // 马达绑定函数 + .Init = InitVibratorDriver, // 马达初始化函数 .Release = ReleaseVibratorDriver, // 马达资源释放函数 }; - + /* 调用HDF_INIT将驱动入口注册到HDF框架中 */ HDF_INIT(g_vibratorDriverEntry); ``` @@ -152,18 +162,19 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 ```c /* 马达设备HCS配置 */ vibrator :: host { - hostName = "vibrator_host"; - device_vibrator :: device { - device0 :: deviceNode { - policy = 2; // 驱动服务发布的策略 - priority = 100; // 驱动启动优先级(0-200),值越大优先级越低,建议配置100,优先级相同则不保证device的加载顺序 - preload = 0; // 驱动按需加载字段,0表示加载,2表示不加载 - permission = 0664; // 驱动创建设备节点权限 - moduleName = "HDF_VIBRATOR"; // 驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 - serviceName = "hdf_misc_vibrator"; // 驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "hdf_vibrator_driver"; // 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值相等 - } - } + hostName = "vibrator_host"; + device_vibrator :: device { + device0 :: deviceNode { + policy = 2; // 驱动服务发布的策略 + priority = 100; // 驱动启动优先级(0-200),值越大优先级越低,建议配置100,优先级相同则不保证device的加载顺序 + preload = 0; // 驱动按需加载字段,0表示加载,2表示不加载 + permission = 0664; // 驱动创建设备节点权限 + moduleName = "HDF_VIBRATOR"; // 驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 + serviceName = "hdf_misc_vibrator"; // 驱动对外发布服务的名称,必须唯一 + deviceMatchAttr = "hdf_vibrator_driver"; // 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值相等 + } + } + } ``` 2. 创建马达效果模型,解析马达效果HCS配置。 @@ -202,23 +213,23 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 } ``` - - 马达效果模型使用HCS作为配置描述源码,hcs配置文件字段详细介绍参考[配置管理](driver-hdf-manage.md)。 + - 马达效果模型使用HCS作为配置描述源码,HCS配置文件字段详细介绍参考[配置管理](driver-hdf-manage.md)。 - ```hcs + ```c /* 马达数据配置模板(vibrator_config.hcs) */ root { vibratorConfig { boardConfig { - match_attr = "hdf_vibrator_driver"; // 需要和马达设备配置match_attr字段保持一致 + match_attr = "hdf_vibrator_driver"; // 需要和马达设备配置文件中的match_attr字段保持一致 vibratorAttr { /* 0:转子;1:线性 */ - deviceType = 1; // 设备类型 - supportPreset = 1; // 支持的预设类型 + deviceType = 1; // 设备类型 + supportPreset = 1; // 支持的预设类型 } vibratorHapticConfig { haptic_clock_timer { effectName = "haptic.clock.timer"; - type = 1; // 0:内置模式;1:时间序列 + type = 1; // 0:内置模式;1:时间序列 seq = [600, 600, 200, 600]; // 时间序列 } haptic_default_effect { @@ -232,9 +243,9 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 } ``` -3. 完成马达振动和停止接口开发,会根据振动效果的模式创建和销毁定时器。 +3. 完成马达信息获取、振动模式设置和停止的接口开发,并实现根据振动模式创建和销毁定时器。 - 马达硬件服务调用StartOnce接口动态配置持续振动时间;调用StartEffect接口启动静态配置的振动效果,为驱动开发者提供抽象的配置接口能力。 + 马达硬件服务调用StartOnce接口动态配置持续振动时间,调用StartEffect接口启动静态配置的振动效果,为驱动开发者提供抽象的配置接口能力。 ```c /* 按照指定持续时间触发振动马达,duration为振动持续时长。 */ @@ -259,7 +270,7 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 return HDF_SUCCESS; } - /* 按照预置效果启动马达,effectType表示预置的预置效果。 */ + /* 按照预置效果启动马达,effectType表示预置的振动效果。 */ static int32_t StartEffect(struct HdfSBuf *data, struct HdfSBuf *reply) { int32_t ret; @@ -313,11 +324,11 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 int32_t intensity; int32_t frequency; int32_t ret; - ..... + ..... (void)OsalMutexLock(&drvData->mutex); drvData->mode = VIBRATOR_MODE_ONCE; (void)OsalMutexUnlock(&drvData->mutex); - /* 设置振幅和频率 */ + /* 设置振幅和频率 */ ret = drvData->ops.SetParameter(intensity, frequency); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: set parameter failed", __func__); @@ -380,7 +391,7 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 } /* 注册马达信息接口 */ - int32_t RegisterVibratorInfo(struct VibratorInfo *vibratorInfo) + int32_t RegisterVibratorInfo(struct VibratorInfo *vibratorInfo) { struct VibratorDriverData *drvData = GetVibratorDrvData(); @@ -407,29 +418,29 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 static int32_t StopModulationParameter() { uint8_t value[DRV2605L_VALUE_BUTT]; - struct Drv2605lDriverData *drvData = NULL; + struct Drv2605lDriverData *drvData = NULL; drvData = GetDrv2605lDrvData(); - CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); + CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData->drv2605lCfgData, HDF_FAILURE); value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_MODE; value[DRV2605L_VALUE_INDEX] = (uint8_t)DRV2605_MODE_STANDBY; if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); - return HDF_FAILURE; + return HDF_FAILURE; } value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_RTPIN; value[DRV2605L_VALUE_INDEX] = (uint8_t)&drvData->drv2605lCfgData->vibratorAttr.defaultIntensity; if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { - HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); + HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); } value[DRV2605L_ADDR_INDEX] = (uint8_t)DRV2605_REG_LRARESON; value[DRV2605L_VALUE_INDEX] = (uint8_t)&drvData->drv2605lCfgData->vibratorAttr.defaultFrequency; if (WriteDrv2605l(&drvData->drv2605lCfgData->vibratorBus.i2cCfg, value, sizeof(value)) != HDF_SUCCESS) { - HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); + HDF_LOGE("%s: i2c addr [%0X] write failed", __func__, value[DRV2605L_ADDR_INDEX]); } return HDF_SUCCESS; @@ -439,7 +450,7 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 static void SetModulationParameter(int32_t intensity, int32_t frequency) { uint8_t value[DRV2605L_VALUE_BUTT]; - struct Drv2605lDriverData *drvData = NULL; + struct Drv2605lDriverData *drvData = NULL; drvData = GetDrv2605lDrvData(); CHECK_VIBRATOR_NULL_PTR_RETURN_VALUE(drvData, HDF_FAILURE); @@ -453,7 +464,7 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 } } else { HDF_LOGD("%s: the setting of intensity 0 is not supported and \ - will be set as the system default intensity", __func__); + will be set as the system default intensity", __func__); } if (frequency != 0) { @@ -472,9 +483,9 @@ Vibrator驱动模型为上层马达硬件服务层提供稳定的马达控制能 ### 调测验证 -驱动开发完成后,在传感器单元测试里面开发自测试用例,验证驱动基本功能。测试环境采用开发者自测试平台。 +驱动开发完成后,在马达单元测试里面开发自测试用例,验证驱动基本功能。测试环境采用开发者自测试平台。 -``` +```c++ /* 用例执行前,初始化马达接口实例。 */ void HdfVibratorTest::SetUpTestCase() { diff --git "a/zh-cn/device-dev/driver/figures/Light\351\251\261\345\212\250\346\250\241\345\236\213\345\233\276.png" "b/zh-cn/device-dev/driver/figures/Light\351\251\261\345\212\250\346\250\241\345\236\213\345\233\276.png" index 77f9bb9f1643e7338043f85c74eee706a0f3561b..569eb41dfbe05aa66cc873e3da02b7834617252c 100644 Binary files "a/zh-cn/device-dev/driver/figures/Light\351\251\261\345\212\250\346\250\241\345\236\213\345\233\276.png" and "b/zh-cn/device-dev/driver/figures/Light\351\251\261\345\212\250\346\250\241\345\236\213\345\233\276.png" differ diff --git a/zh-cn/device-dev/get-code/sourcecode-acquire.md b/zh-cn/device-dev/get-code/sourcecode-acquire.md index 7fb9f4c4c51323d740ad6cf5d3da5bed2d20fbec..b341943bb88fe552c418b6426e560cb484105869 100644 --- a/zh-cn/device-dev/get-code/sourcecode-acquire.md +++ b/zh-cn/device-dev/get-code/sourcecode-acquire.md @@ -12,7 +12,7 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及 ## 获取源码概述 -本文档将介绍如何获取OpenHarmony源码并说明OpenHarmony的源码目录结构。OpenHarmony的代码以[组件](../hpm-part/Readme-CN.md)的形式开放,开发者可以通过如下其中一种方式获取: +本文档将介绍如何获取OpenHarmony源码并说明OpenHarmony的源码目录结构。OpenHarmony的代码以[组件](../hpm-part/hpm-part-about.md)的形式开放,开发者可以通过如下其中一种方式获取: - **获取方式1**:从码云代码仓库获取。通过repo或git工具从代码仓库中下载,此方式可获取最新代码。 @@ -77,7 +77,12 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> Master主干为开发分支,开发者可通过Master主干获取最新特性。发布版本代码相对比较稳定,开发者可基于发布版本代码进行商用功能开发。 +> +> 发布版本代码相对比较稳定,开发者可基于发布版本代码进行商用功能开发。Master主干为开发分支,开发者可通过Master主干获取最新特性。 + +- **OpenHarmony发布版本代码获取** + + OpenHarmony发布版本获取源码方式请参考[Release Notes](../../release-notes/Readme.md)。 - **OpenHarmony主干代码获取** @@ -98,10 +103,6 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及 repo forall -c 'git lfs pull' ``` -- **OpenHarmony发布版本代码获取** - - OpenHarmony发布版本获取源码方式请参考[Release Notes](../../release-notes/Readme.md)。 - ## 获取方式2:从DevEco Marketplace获取 diff --git a/zh-cn/device-dev/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index d243354b9c95f462dcddd8fcb6ef7acd396b62d9..d2f636772b96b25854cf596fcb122bc9c08a561b 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -13,8 +13,9 @@ - [互斥锁](kernel-mini-basic-ipc-mutex.md) - [消息队列](kernel-mini-basic-ipc-queue.md) - [信号量](kernel-mini-basic-ipc-sem.md) - - [时间管理](kernel-basic-mini-time.md) + - [时间管理](kernel-mini-basic-time.md) - [软件定时器](kernel-mini-basic-soft.md) + - [双向链表](kernel-mini-basic-list.md) - 扩展组件 - [C++支持](kernel-mini-extend-support.md) - [CPU占用率](kernel-mini-extend-cpup.md) @@ -27,7 +28,6 @@ - [LMS调测](kernel-mini-memory-lms.md) - 附录 - [内核编码规范](kernel-mini-appx-code.md) - - [双向链表](kernel-mini-appx-data-list.md) - [标准库支持](kernel-mini-appx-lib.md) - 小型系统内核(LiteOS-A) - [小型系统内核概述](kernel-small-overview.md) diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220915165414926.png b/zh-cn/device-dev/kernel/figures/zh-cn_image-20220915165414926.png index 5635e7de0f5ff8a0f02fe778c5f38803e3f1b05a..7148fff059e2c3628fd9c2911cfabd969f81fdb8 100644 Binary files a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220915165414926.png and b/zh-cn/device-dev/kernel/figures/zh-cn_image-20220915165414926.png differ diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930113757464.png b/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930113757464.png deleted file mode 100644 index 642e0f6c3f63238df8b6d49ea59b9b7f8c0eb01e..0000000000000000000000000000000000000000 Binary files a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930113757464.png and /dev/null differ diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png b/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png index 4a959db1206c500c0ee61e1548ffa4c94565d104..f4c4e437a0089ac5ba3371f531694daac4b36703 100644 Binary files a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png and b/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png differ diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image-20221009112548444.png b/zh-cn/device-dev/kernel/figures/zh-cn_image-20221009112548444.png index 0c4e83fda3b7ea5f356dfb96950b14180b087afb..0693d37d2e8869bea0c09e26bd247f23d527f90c 100644 Binary files a/zh-cn/device-dev/kernel/figures/zh-cn_image-20221009112548444.png and b/zh-cn/device-dev/kernel/figures/zh-cn_image-20221009112548444.png differ diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md b/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md index 9c8e2e42ded8903ddaa5a864aea95bef8990e043..eaa1f10f6dc98b1ac1b6d6ddbda1d47af85fbf04 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md @@ -9,25 +9,25 @@ 下面介绍下中断的相关概念: -- 中断号 +- 中断号: 中断请求信号特定的标志,计算机能够根据中断号判断是哪个设备提出的中断请求。 -- 中断请求 +- 中断请求: “紧急事件”向CPU提出申请(发一个电脉冲信号),请求中断,需要CPU暂停当前执行的任务处理该“紧急事件”,这一过程称为中断请求。 -- 中断优先级 +- 中断优先级: 为使系统能够及时响应并处理所有中断,系统根据中断事件的重要性和紧迫程度,将中断源分为若干个级别,称作中断优先级。 -- 中断处理程序 +- 中断处理程序: 当外设发出中断请求后,CPU暂停当前的任务,转而响应中断请求,即执行中断处理程序。产生中断的每个设备都有相应的中断处理程序。 -- 中断触发 +- 中断触发: 中断源向中断控制器发送中断信号,中断控制器对中断进行仲裁,确定优先级,将中断信号发送给CPU。中断源产生中断信号的时候,会将中断触发器置“1”,表明该中断源产生了中断,要求CPU去响应该中断。 -- 中断向量 +- 中断向量: 中断服务程序的入口地址。 -- 中断向量表 +- 中断向量表: 存储中断向量的存储区,中断向量与中断号对应,中断向量在中断向量表中按照中断号顺序存储。 @@ -37,37 +37,46 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 **表1** 创建、删除中断 -| 接口名 | 描述 | +| 接口名 | 描述 | | -------- | -------- | -| HalHwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 | -| HalHwiDelete | 根据指定的中断号,删除中断。 | +| LOS_HwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 | +| LOS_HwiDelete | 根据指定的中断号,删除中断。 | **表2** 打开、关闭中断 -| 接口名 | 描述 | +| 接口名 | 描述 | | -------- | -------- | -| LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 | -| LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 | -| LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 | +| LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 | +| LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 | +| LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 | + + **表3** 其他中断操作 + +| 接口名 | 描述 | +| :----------------- | ---------------- | +| LOS_HwiTrigger | 中断触发。 | +| LOS_HwiEnable | 中断使能。 | +| LOS_HwiDisable | 中断禁用。 | +| LOS_HwiClear | 中断手动清除。 | +| LOS_HwiSetPriority | 设置中断优先级。 | +| LOS_HwiCurIrqNum | 获取当前中断号。 | ## 开发流程 -1. 调用中断创建接口HalHwiCreate创建中断。 +1. 调用中断创建接口LOS_HwiCreate创建中断。 -2. 调用TestHwiTrigger接口触发指定中断(该接口在测试套中定义,通过写中断控制器的相关寄存器模拟外部中断,一般的外设设备,不需要执行这一步)。 +2. 调用LOS_HwiTrigger接口触发指定中断(写中断控制器的相关寄存器模拟外部中断),或通过外设触发中断。 -3. 调用HalHwiDelete接口删除指定中断,此接口根据实际情况使用,判断是否需要删除中断。 +3. 调用LOS_HwiDelete接口删除指定中断,此接口根据实际情况使用,开发者判断是否需要删除中断。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > - 根据具体硬件,配置支持的最大中断数及可设置的中断优先级个数。 -> -> - 中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。 -> +> - 关中断时间或中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。 > - 中断响应过程中不能直接、间接执行引起调度的LOS_Schedule等函数。 -> -> - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。 +> - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。 +> - Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。 ## 编程实例 @@ -80,29 +89,39 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 3. 删除中断。 -代码实现如下,演示如何创建中断和删除中断,当指定的中断号HWI_NUM_TEST产生中断时,会调用中断处理函数: +代码实现如下,演示如何创建中断、触发指定的中断号进而调用中断处理函数、删除中断。 + +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleInterrupt。 + - ``` #include "los_interrupt.h" +#include "los_compiler.h" -/*创建中断*/ +/* 验证的中断号 */ #define HWI_NUM_TEST 7 -STATIC VOID HwiUsrIrq(VOID) +/* 中断处理程序 */ +STATIC VOID UsrIrqEntry(VOID) { - printf("in the func HwiUsrIrq \n"); + printf("in the func UsrIrqEntry\n"); } -static UINT32 Example_Interrupt(VOID) +/* 注册的线程回调函数,用于触发中断 */ +STATIC VOID InterruptTest(VOID) +{ + LOS_HwiTrigger(HWI_NUM_TEST); +} + +UINT32 ExampleInterrupt(VOID) { UINT32 ret; - HWI_PRIOR_T hwiPrio = 3; + HWI_PRIOR_T hwiPrio = 3; // 3,中断优先级 HWI_MODE_T mode = 0; HWI_ARG_T arg = 0; - - /*创建中断*/ - ret = HalHwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, arg); + + /* 创建中断 */ + ret = LOS_HwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)UsrIrqEntry, arg); if(ret == LOS_OK){ printf("Hwi create success!\n"); } else { @@ -110,17 +129,32 @@ static UINT32 Example_Interrupt(VOID) return LOS_NOK; } - /* 延时50个Ticks, 当有硬件中断发生时,会调用函数HwiUsrIrq*/ + TSK_INIT_PARAM_S taskParam = { 0 }; + UINT32 testTaskID; + + /* 创建一个优先级低优先级的线程,用于验证触发中断 */ + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)InterruptTest; + taskParam.uwStackSize = OS_TSK_TEST_STACK_SIZE; + taskParam.pcName = "InterruptTest"; + taskParam.usTaskPrio = TASK_PRIO_TEST - 1; + taskParam.uwResved = LOS_TASK_ATTR_JOINABLE; + ret = LOS_TaskCreate(&testTaskID, &taskParam); + if (LOS_OK != ret) { + PRINTF("InterruptTest task error\n"); + } + + /* 延时50 tick,让出当前线程的调度 */ LOS_TaskDelay(50); - /*删除中断*/ - ret = HalHwiDelete(HWI_NUM_TEST); + /* 删除注册的中断 */ + ret = LOS_HwiDelete(HWI_NUM_TEST, NULL); if(ret == LOS_OK){ printf("Hwi delete success!\n"); } else { printf("Hwi delete failed!\n"); return LOS_NOK; } + return LOS_OK; } ``` @@ -131,8 +165,9 @@ static UINT32 Example_Interrupt(VOID) 编译运行得到的结果为: - + ``` Hwi create success! +in the func UsrIrqEntry Hwi delete success! ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md index 3f22c8ca8805c838933f2a66cead333a6ae34e04..ef398c91849fcae751bcb1c848424acaa609772d 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md @@ -16,14 +16,12 @@ ## 运行机制 - ### 事件控制块 +由事件初始化函数配置的一个结构体,在事件读写等操作时作为参数传入,用于标识不同的事件,控制块数据结构如下: + ``` -/** - * 事件控制块数据结构 - */ typedef struct tagEvent { UINT32 uwEventID; /* 事件集合,表示已经处理(写入和清零)的事件集合 */ LOS_DL_LIST stEventList; /* 等待特定事件的任务链表 */ @@ -33,7 +31,7 @@ typedef struct tagEvent { ### 事件运作原理 -**事件初始化**:会创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。 +**事件初始化**:创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。 **写事件**:会向事件控制块写入指定的事件,事件控制块更新事件集合,并遍历任务链表,根据任务等待具体条件满足情况决定是否唤醒相关任务。 @@ -96,31 +94,29 @@ typedef struct tagEvent { ### 实例描述 -示例中,任务Example_TaskEntry创建一个任务Example_Event,Example_Event读事件阻塞,Example_TaskEntry向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。 +示例中,任务ExampleEvent创建一个任务EventReadTask,EventReadTask读事件阻塞,ExampleEvent向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。 -1. 在任务Example_TaskEntry创建任务Example_Event,其中任务Example_Event优先级高于Example_TaskEntry。 +1. 在任务ExampleEvent创建任务EventReadTask,其中任务EventReadTask优先级高于ExampleEvent。 -2. 在任务Example_Event中读事件0x00000001,阻塞,发生任务切换,执行任务Example_TaskEntry。 +2. 在任务EventReadTask中读事件0x00000001,阻塞,发生任务切换,执行任务ExampleEvent。 -3. 在任务Example_TaskEntry向任务Example_Event写事件0x00000001,发生任务切换,执行任务Example_Event。 +3. 在任务ExampleEvent写事件0x00000001,发生任务切换,执行任务EventReadTask。 -4. Example_Event得以执行,直到任务结束。 +4. EventReadTask得以执行,直到任务结束。 -5. Example_TaskEntry得以执行,直到任务结束。 +5. ExampleEvent得以执行,直到任务结束。 ### 示例代码 示例代码如下: +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleEvent。 + ``` #include "los_event.h" #include "los_task.h" -#include "securec.h" - -/* 任务ID */ -UINT32 g_testTaskId; /* 事件控制结构体 */ EVENT_CB_S g_exampleEvent; @@ -128,8 +124,11 @@ EVENT_CB_S g_exampleEvent; /* 等待的事件类型 */ #define EVENT_WAIT 0x00000001 +/* 等待超时时间 */ +#define EVENT_TIMEOUT 100 + /* 用例任务入口函数 */ -VOID Example_Event(VOID) +VOID EventReadTask(VOID) { UINT32 ret; UINT32 event; @@ -137,39 +136,39 @@ VOID Example_Event(VOID) /* 超时等待方式读事件,超时时间为100 ticks, 若100 ticks后未读取到指定事件,读事件超时,任务直接唤醒 */ printf("Example_Event wait event 0x%x \n", EVENT_WAIT); - event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, 100); + event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, EVENT_TIMEOUT); if (event == EVENT_WAIT) { - printf("Example_Event,read event :0x%x\n", event); + printf("Example_Event, read event :0x%x\n", event); } else { - printf("Example_Event,read event timeout\n"); + printf("Example_Event, read event timeout\n"); } } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleEvent(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; + UINT32 taskId; + TSK_INIT_PARAM_S taskParam = { 0 }; /* 事件初始化 */ ret = LOS_EventInit(&g_exampleEvent); if (ret != LOS_OK) { printf("init event failed .\n"); - return -1; + return LOS_NOK; } /* 创建任务 */ - (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Event; - task1.pcName = "EventTsk1"; - task1.uwStackSize = OS_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId, &task1); + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)EventReadTask; + taskParam.pcName = "EventReadTask"; + taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam.usTaskPrio = 3; + ret = LOS_TaskCreate(&taskId, &taskParam); if (ret != LOS_OK) { printf("task create failed.\n"); return LOS_NOK; } - /* 写g_testTaskId 等待事件 */ + /* 写事件 */ printf("Example_TaskEntry write event.\n"); ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT); @@ -183,10 +182,10 @@ UINT32 Example_TaskEntry(VOID) LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID); printf("EventMask:%d\n", g_exampleEvent.uwEventID); - /* 删除任务 */ - ret = LOS_TaskDelete(g_testTaskId); + /* 删除事件 */ + ret = LOS_EventDestroy(&g_exampleEvent); if (ret != LOS_OK) { - printf("task delete failed.\n"); + printf("destory event failed .\n"); return LOS_NOK; } @@ -202,9 +201,9 @@ UINT32 Example_TaskEntry(VOID) ``` -Example_Event wait event 0x1 +Example_Event wait event 0x1 Example_TaskEntry write event. -Example_Event,read event :0x1 +Example_Event, read event :0x1 EventMask:1 EventMask:0 ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md index 77b90fb2079a1ea453acde1d4a85ec13270de23e..79fcfd6af0e111bb78184246260a3777afc95d9e 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md @@ -5,7 +5,7 @@ 互斥锁又称互斥型信号量,是一种特殊的二值性信号量,用于实现对共享资源的独占式处理。 -任意时刻互斥锁的状态只有两种,开锁或闭锁。当有任务持有时,互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放它时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。 +任意时刻互斥锁的状态只有两种,开锁或闭锁。当任务持有互斥锁时,该互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放互斥锁时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。 多任务环境下往往存在多个任务竞争同一共享资源的应用场景,互斥锁可被用于对共享资源的保护从而实现独占式访问。另外互斥锁可以解决信号量存在的优先级翻转问题。 @@ -24,10 +24,10 @@ **表1** 互斥锁模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁
LOS_MuxDelete:删除指定的互斥锁 | -| 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁
LOS_MuxPost:释放指定的互斥锁 | +| 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁。
LOS_MuxDelete:删除指定的互斥锁。 | +| 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁。
LOS_MuxPost:释放指定的互斥锁。 | ## 开发流程 @@ -39,7 +39,7 @@ 2. 申请互斥锁LOS_MuxPend。 申请模式有三种:无阻塞模式、永久阻塞模式、定时阻塞模式。 - - 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。 + - 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。否则直接返回并继续运行当前任务,不会产生阻塞。 - 永久阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则,该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,直到有其他任务释放该互斥锁,阻塞任务才会重新得以执行。 - 定时阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,指定时间超时前有其他任务释放该互斥锁,或者用户指定时间超时后,阻塞任务才会重新得以执行。 @@ -50,7 +50,7 @@ 4. 删除互斥锁LOS_MuxDelete。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 两个任务不能对同一把互斥锁加锁。如果某任务对已被持有的互斥锁加锁,则该任务会被挂起,直到持有该锁的任务对互斥锁解锁,才能执行对这把互斥锁的加锁操作。 +> - 互斥锁支持嵌套,即申请该互斥锁的任务与已经持有该互斥锁的任务为同一个任务时会认为申请成功,按申请次数对应的去释放该锁即可。 > > - 互斥锁不能在中断服务程序中使用。 > @@ -66,67 +66,66 @@ 本实例实现如下流程。 -1. 任务Example_TaskEntry创建一个互斥锁,锁任务调度,创建两个任务Example_MutexTask1、Example_MutexTask2。Example_MutexTask2优先级高于Example_MutexTask1,解锁任务调度。 +1. 任务ExampleMutex创建一个互斥锁,锁任务调度,创建两个任务ExampleMutexTask1、ExampleMutexTask2。ExampleMutexTask2优先级高于ExampleMutexTask1,解锁任务调度。 -2. Example_MutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,Example_MutexTask2挂起,Example_MutexTask1被唤醒。 +2. ExampleMutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,ExampleMutexTask2挂起,ExampleMutexTask1被唤醒。 -3. Example_MutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。10Tick超时时间到达后,Example_MutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。 +3. ExampleMutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。10Tick超时时间到达后,ExampleMutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。 -4. 100Tick休眠时间到达后,Example_MutexTask2被唤醒, 释放互斥锁,唤醒Example_MutexTask1。Example_MutexTask1成功获取到互斥锁后,释放,删除互斥锁。 +4. 100Tick休眠时间到达后,ExampleMutexTask2被唤醒, 释放互斥锁,唤醒ExampleMutexTask1。ExampleMutexTask1成功获取到互斥锁后,释放并删除互斥锁。 ### 示例代码 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleMutex。 + + ``` -#include #include "los_mux.h" -/* 互斥锁句柄id */ +/* 互斥锁句柄 */ UINT32 g_testMux; -/* 任务ID */ -UINT32 g_testTaskId01; -UINT32 g_testTaskId02; -VOID Example_MutexTask1(VOID) +VOID ExampleMutexTask1(VOID) { UINT32 ret; printf("task1 try to get mutex, wait 10 ticks.\n"); /* 申请互斥锁 */ ret = LOS_MuxPend(g_testMux, 10); - if (ret == LOS_OK) { printf("task1 get mutex g_testMux.\n"); - /* 释放互斥锁 */ + /* 释放互斥锁,这个分支正常不应该进来 */ LOS_MuxPost(g_testMux); + LOS_MuxDelete(g_testMux); return; - } + } + if (ret == LOS_ERRNO_MUX_TIMEOUT ) { - printf("task1 timeout and try to get mutex, wait forever.\n"); - /* 申请互斥锁 */ - ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("task1 wait forever, get mutex g_testMux.\n"); - /* 释放互斥锁 */ - LOS_MuxPost(g_testMux); - /* 删除互斥锁 */ - LOS_MuxDelete(g_testMux); - printf("task1 post and delete mutex g_testMux.\n"); - return; - } + printf("task1 timeout and try to get mutex, wait forever.\n"); + /* 申请互斥锁 */ + ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); + if (ret == LOS_OK) { + printf("task1 wait forever, get mutex g_testMux.\n"); + /* 释放互斥锁 */ + LOS_MuxPost(g_testMux); + /* 删除互斥锁 */ + LOS_MuxDelete(g_testMux); + printf("task1 post and delete mutex g_testMux.\n"); + return; + } } + return; } -VOID Example_MutexTask2(VOID) +VOID ExampleMutexTask2(VOID) { printf("task2 try to get mutex, wait forever.\n"); /* 申请互斥锁 */ (VOID)LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); - printf("task2 get mutex g_testMux and suspend 100 ticks.\n"); /* 任务休眠100Ticks */ @@ -138,11 +137,13 @@ VOID Example_MutexTask2(VOID) return; } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleMutex(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; - TSK_INIT_PARAM_S task2; + TSK_INIT_PARAM_S task1 = { 0 }; + TSK_INIT_PARAM_S task2 = { 0 }; + UINT32 taskId01; + UINT32 taskId02; /* 创建互斥锁 */ LOS_MuxCreate(&g_testMux); @@ -151,24 +152,22 @@ UINT32 Example_TaskEntry(VOID) LOS_TaskLock(); /* 创建任务1 */ - memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask1; + task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask1; task1.pcName = "MutexTsk1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + ret = LOS_TaskCreate(&taskId01, &task1); if (ret != LOS_OK) { printf("task1 create failed.\n"); return LOS_NOK; } /* 创建任务2 */ - memset(&task2, 0, sizeof(TSK_INIT_PARAM_S)); - task2.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask2; + task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask2; task2.pcName = "MutexTsk2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task2.usTaskPrio = 4; - ret = LOS_TaskCreate(&g_testTaskId02, &task2); + ret = LOS_TaskCreate(&taskId02, &task2); if (ret != LOS_OK) { printf("task2 create failed.\n"); return LOS_NOK; @@ -185,7 +184,7 @@ UINT32 Example_TaskEntry(VOID) ### 结果验证 编译运行得到的结果为: - + ``` task2 try to get mutex, wait forever. task2 get mutex g_testMux and suspend 100 ticks. diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md index 16178ecadabea0217f49780744c8d272bc39d590..f2e60ebd8b30ea049f5238dbd1ae52bc17e40ec9 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md @@ -3,7 +3,7 @@ ## 基本概念 -队列又称消息队列,是一种常用于任务间通信的数据结构。队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。 +消息队列又称队列,是一种任务间通信的机制。消息队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。 任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。 @@ -12,44 +12,40 @@ 消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性: - 消息以先进先出的方式排队,支持异步读写。 - - 读队列和写队列都支持超时机制。 - - 每读取一条消息,就会将该消息节点设置为空闲。 - - 发送消息类型由通信双方约定,可以允许不同长度(不超过队列的消息节点大小)的消息。 - - 一个任务能够从任意一个消息队列接收和发送消息。 - - 多个任务能够从同一个消息队列接收和发送消息。 - -- 创建队列时所需的队列空间,接口内系统自行动态申请内存。 +- 创建普通队列时所需的队列空间,由系统自行动态申请内存。 +- 创建静态队列时所需的队列空间,由用户传入。这块空间在队列删除之后也由用户去释放。 ## 运行机制 - ### 队列控制块 - +队列会在初始化时给分配一个属于自己的控制块,控制块包含了队列的名称、状态等信息。删除队列时会释放该控制块。 + +队列控制块数据结构如下: + + ``` -/** - * 队列控制块数据结构 - */ typedef struct { - UINT8 *queue; /* 队列消息内存空间的指针 */ - UINT16 queueState; /* 队列状态 */ - UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */ - UINT16 queueSize; /* 消息节点大小 */ - UINT16 queueID; /* 队列ID */ - UINT16 queueHead; /* 消息头节点位置(数组下标)*/ - UINT16 queueTail; /* 消息尾节点位置(数组下标)*/ - UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数, - 数组下标1的元素表示队列中可写消息数 */ - LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表, - 下标0:读取链表,下标1:写入链表 */ - LOS_DL_LIST memList; /* 内存块链表 */ + UINT8 *queue; /* 队列消息内存空间的指针 */ + UINT8 *queueName /* 队列名称 */ + UINT16 queueState; /* 队列状态 */ + UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */ + UINT16 queueSize; /* 消息节点大小 */ + UINT16 queueID; /* 队列ID */ + UINT16 queueHead; /* 消息头节点位置(数组下标)*/ + UINT16 queueTail; /* 消息尾节点位置(数组下标)*/ + UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数, + 数组下标1的元素表示队列中可写消息数 */ + LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表, + 下标0:读取链表,下标1:写入链表 */ + LOS_DL_LIST memList; /* 内存块链表 */ } LosQueueCB; ``` @@ -81,12 +77,12 @@ typedef struct ## 接口说明 - | 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建/删除消息队列 | - LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。
- LOS_QueueDelete:根据队列ID删除一个指定队列。 | -| 读/写队列(不带拷贝) | - LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。
- LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。
- LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 | -| 读/写队列(带拷贝) | - LOS_QueueReadCopy:读取指定队列头节点中的数据。
- LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。
- LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 | -| 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 | +| 创建/删除消息队列 |  LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。
LOS_QueueCreateStatic:创建一个消息队列,由用户传入队列空间。
 LOS_QueueDelete:根据队列ID删除一个指定队列,静态消息队列删除后,队列空间需要用例自行处理。 | +| 读/写队列(不带拷贝) |  LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。
 LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。
 LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 | +| 读/写队列(带拷贝) |  LOS_QueueReadCopy:读取指定队列头节点中的数据。
 LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。
 LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 | +| 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 | ## 开发流程 @@ -140,11 +136,14 @@ typedef struct 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleQueue。 + + ``` #include "los_task.h" #include "los_queue.h" -static UINT32 g_queue; + +STATIC UINT32 g_queue; #define BUFFER_LEN 50 VOID SendEntry(VOID) @@ -154,7 +153,7 @@ VOID SendEntry(VOID) UINT32 len = sizeof(abuf); ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("send message failure, error: %x\n", ret); } } @@ -165,17 +164,17 @@ VOID RecvEntry(VOID) CHAR readBuf[BUFFER_LEN] = {0}; UINT32 readLen = BUFFER_LEN; - //休眠1s + /* 休眠1s */ usleep(1000000); ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("recv message failure, error: %x\n", ret); } - printf("recv message: %s\n", readBuf); + printf("recv message: %s.\n", readBuf); ret = LOS_QueueDelete(g_queue); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("delete the queue failure, error: %x\n", ret); } @@ -186,25 +185,28 @@ UINT32 ExampleQueue(VOID) { printf("start queue example.\n"); UINT32 ret = 0; - UINT32 task1, task2; - TSK_INIT_PARAM_S initParam = {0}; - - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; - initParam.usTaskPrio = 9; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - initParam.pcName = "SendQueue"; + UINT32 task1; + UINT32 task2; + TSK_INIT_PARAM_S taskParam1 = { 0 }; + TSK_INIT_PARAM_S taskParam2 = { 0 }; LOS_TaskLock(); - ret = LOS_TaskCreate(&task1, &initParam); + + taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; + taskParam1.usTaskPrio = 9; + taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam1.pcName = "SendQueue"; + ret = LOS_TaskCreate(&task1, &taskParam1); if(ret != LOS_OK) { printf("create task1 failed, error: %x\n", ret); return ret; } - initParam.pcName = "RecvQueue"; - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; - initParam.usTaskPrio = 10; - ret = LOS_TaskCreate(&task2, &initParam); + taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; + taskParam2.usTaskPrio = 10; + taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam2.pcName = "RecvQueue"; + ret = LOS_TaskCreate(&task2, &taskParam2); if(ret != LOS_OK) { printf("create task2 failed, error: %x\n", ret); return ret; @@ -227,7 +229,7 @@ UINT32 ExampleQueue(VOID) 编译运行得到的结果为: - + ``` start queue example. create the queue success. diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md index 2fb49adb65c17d90504ac54465011f5099760734..b8451b04faa305154792a40778388031158a2e63 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md @@ -11,7 +11,7 @@ - 正值,表示该信号量当前可被获取。 -以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同: +信号量可用于同步或者互斥。以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同: - 用作互斥时,初始信号量计数值不为0,表示可用的共享资源个数。在需要使用共享资源前,先获取信号量,然后使用一个共享资源,使用完毕后释放信号量。这样在共享资源被取完,即信号量计数减至0时,其他需要获取信号量的任务将被阻塞,从而保证了共享资源的互斥访问。另外,当共享资源数为1时,建议使用二值信号量,一种类似于互斥锁的机制。 @@ -23,7 +23,7 @@ ### 信号量控制块 - + ``` /** * 信号量控制块数据结构 @@ -40,7 +40,7 @@ typedef struct { ### 信号量运作原理 -信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。 +信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现,按产品实际需要设定),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。 信号量创建,从未使用的信号量链表中获取一个信号量,并设定初值。 @@ -58,10 +58,10 @@ typedef struct { ## 接口说明 - | 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建/删除信号量 | - LOS_SemCreate:创建信号量,返回信号量ID
- LOS_BinarySemCreate:创建二值信号量,其计数值最大为1
- LOS_SemDelete:删除指定的信号量 | -| 申请/释放信号量 | - LOS_SemPend:申请指定的信号量,并设置超时时间
- LOS_SemPost:释放指定的信号量 | +| 创建/删除信号量 |  LOS_SemCreate:创建信号量,返回信号量ID。
 LOS_BinarySemCreate:创建二值信号量,其计数值最大为1。
 LOS_SemDelete:删除指定的信号量。 | +| 申请/释放信号量 |  LOS_SemPend:申请指定的信号量,并设置超时时间。
 LOS_SemPost:释放指定的信号量。 | ## 开发流程 @@ -101,17 +101,11 @@ typedef struct { 示例代码如下: - -``` -#include "los_sem.h" -#include "securec.h" +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSem。 -/* 任务ID */ -static UINT32 g_testTaskId01; -static UINT32 g_testTaskId02; -/* 测试任务优先级 */ -#define TASK_PRIO_TEST 5 +``` +#include "los_sem.h" /* 信号量结构体id */ static UINT32 g_semId; @@ -121,19 +115,17 @@ VOID ExampleSemTask1(VOID) UINT32 ret; printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); - /* 定时阻塞模式申请信号量,定时时间为10ticks */ ret = LOS_SemPend(g_semId, 10); - /* 申请到信号量 */ if (ret == LOS_OK) { LOS_SemPost(g_semId); return; } + /* 定时时间到,未申请到信号量 */ if (ret == LOS_ERRNO_SEM_TIMEOUT) { printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); - /*永久阻塞模式申请信号量*/ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); printf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); @@ -151,15 +143,14 @@ VOID ExampleSemTask2(VOID) /* 永久阻塞模式申请信号量 */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); } /* 任务休眠20 ticks */ LOS_TaskDelay(20); - printf("ExampleSemTask2 post sem g_semId.\n"); + /* 释放信号量 */ LOS_SemPost(g_semId); return; @@ -168,8 +159,10 @@ VOID ExampleSemTask2(VOID) UINT32 ExampleSem(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; - TSK_INIT_PARAM_S task2; + TSK_INIT_PARAM_S task1 = { 0 }; + TSK_INIT_PARAM_S task2 = { 0 }; + UINT32 taskId1; + UINT32 taskId2; /* 创建信号量 */ LOS_SemCreate(0, &g_semId); @@ -178,24 +171,22 @@ UINT32 ExampleSem(VOID) LOS_TaskLock(); /* 创建任务1 */ - (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1; task1.pcName = "TestTask1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = TASK_PRIO_TEST; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + task1.usTaskPrio = 5; + ret = LOS_TaskCreate(&taskId1, &task1); if (ret != LOS_OK) { printf("task1 create failed.\n"); return LOS_NOK; } /* 创建任务2 */ - (VOID)memset_s(&task2, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2; task2.pcName = "TestTask2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task2.usTaskPrio = (TASK_PRIO_TEST - 1); - ret = LOS_TaskCreate(&g_testTaskId02, &task2); + task2.usTaskPrio = 4; + ret = LOS_TaskCreate(&taskId2, &task2); if (ret != LOS_OK) { printf("task2 create failed.\n"); return LOS_NOK; @@ -221,12 +212,11 @@ UINT32 ExampleSem(VOID) 编译运行得到的结果为: - + ``` ExampleSemTask2 try get sem g_semId wait forever. -ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 try get sem g_semId, timeout 10 ticks. - +ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 timeout and try get sem g_semId wait forever. ExampleSemTask2 post sem g_semId. ExampleSemTask1 wait_forever and get sem g_semId. diff --git a/zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md b/zh-cn/device-dev/kernel/kernel-mini-basic-list.md similarity index 58% rename from zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md rename to zh-cn/device-dev/kernel/kernel-mini-basic-list.md index f0c0d1cbea02488cccc34c8959d348ef15ad7ed5..ec6ae58a9befafbe9cc7868871003073c1702f80 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-list.md @@ -12,16 +12,16 @@ 双向链表模块为用户提供下面几种功能,接口详细信息可以查看API参考。 - | | | +| | | | -------- | -------- | -| **功能分类** | **接口描述** | -| 初始化链表 | - LOS_ListInit:将指定双向链表节点初始化为双向链表
- LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表 | -| 增加节点 | - LOS_ListAdd:将指定节点插入到双向链表头端
- LOS_ListTailInsert:将指定节点插入到双向链表尾端 | -| 删除节点 | - LOS_ListDelete:将指定节点从链表中删除
- LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 | -| 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空 | -| 获取结构体信息 | - LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量 | -| 遍历双向链表 | - LOS_DL_LIST_FOR_EACH:遍历双向链表
- LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 | -| 遍历包含双向链表的结构体 | - LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址
- LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 | +| **功能分类** | **接口描述** | +| 初始化和删除链表 |  LOS_ListInit:将指定双向链表节点初始化为双向链表。
 LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表。
LOS_ListDelInit:删除指定的双向链表。 | +| 增加节点 |  LOS_ListAdd:将指定节点插入到双向链表头端。
 LOS_ListTailInsert:将指定节点插入到双向链表尾端。 | +| 删除节点 |  LOS_ListDelete:将指定节点从链表中删除。
 LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表。 | +| 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空。 | +| 获取结构体信息 |  LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。
 LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量。 | +| 遍历双向链表 |  LOS_DL_LIST_FOR_EACH:遍历双向链表。
 LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验。 | +| 遍历包含双向链表的结构体 |  LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址。
 LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址。 | ## 开发流程 @@ -69,22 +69,24 @@ 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleList。 + + ``` #include "stdio.h" #include "los_list.h" -static UINT32 ListSample(VOID) +STATIC UINT32 ExampleList(VOID) { LOS_DL_LIST listHead = {NULL,NULL}; LOS_DL_LIST listNode1 = {NULL,NULL}; LOS_DL_LIST listNode2 = {NULL,NULL}; - //首先初始化链表 + /* 初始化链表 */ printf("Initial head\n"); LOS_ListInit(&listHead); - //添加节点1和节点2,并校验他们的相互关系 + /* 添加节点1和节点2,并校验他们的相互关系 */ LOS_ListAdd(&listHead, &listNode1); if (listNode1.pstNext == &listHead && listNode1.pstPrev == &listHead) { printf("Add listNode1 success\n"); @@ -95,11 +97,11 @@ static UINT32 ListSample(VOID) printf("Tail insert listNode2 success\n"); } - //删除两个节点 + /* 删除两个节点 */ LOS_ListDelete(&listNode1); LOS_ListDelete(&listNode2); - //确认链表为空 + /* 确认链表为空 */ if (LOS_ListEmpty(&listHead)) { printf("Delete success\n"); } @@ -113,7 +115,7 @@ static UINT32 ListSample(VOID) 编译运行得到的结果为: - + ``` Initial head Add listNode1 success diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md index 5071ddf325680c7d939907b5bb2fd8d8f1368e77..a95eb894ce9723b9ae74c39efd8e23fd6e87263e 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md @@ -45,12 +45,12 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 **表1** 静态内存模块接口 -| 功能分类 | 接口名 | +| 功能分类 | 接口名 | | -------- | -------- | -| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | -| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | -| 申请、释放静态内存 | - LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
- LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | -| 获取、打印静态内存池信息 | - LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
- LOS_ShowBox:打印指定静态内存池所有节点信息(打印等级是LOS_INFO_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | +| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | +| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | +| 申请、释放静态内存 |  LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
 LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | +| 获取、打印静态内存池信息 |  LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
 LOS_ShowBox:打印指定静态内存池所有节点信息,打印等级是LOG_INFO_LEVEL(当前打印等级配置是PRINT_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 初始化后的内存池的内存块数量,不等于总大小除于内存块大小,因为内存池的控制块和每个内存块的控制头,都存在内存开销,设置总大小时,需要将这些因素考虑进去。 @@ -91,21 +91,26 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 6. 释放该内存块。 示例代码如下: + + 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleStaticMem。 + - ``` #include "los_membox.h" -VOID Example_StaticMem(VOID) +#define MEMBOX_POOL_SIZE 100 +#define MEMBOX_BLOCK_SZIE 10 +#define MEMBOX_WR_TEST_NUM 828 +VOID ExampleStaticMem(VOID) { UINT32 *mem = NULL; - UINT32 blkSize = 10; - UINT32 boxSize = 100; - UINT32 boxMem[1000]; + UINT32 blkSize = MEMBOX_BLOCK_SZIE; + UINT32 poolSize = MEMBOX_POOL_SIZE; + UINT32 boxMem[MEMBOX_POOL_SIZE]; UINT32 ret; - /*内存池初始化*/ - ret = LOS_MemboxInit(&boxMem[0], boxSize, blkSize); + /* 内存池初始化 */ + ret = LOS_MemboxInit(&boxMem[0], poolSize, blkSize); if(ret != LOS_OK) { printf("Membox init failed!\n"); return; @@ -113,23 +118,23 @@ VOID Example_StaticMem(VOID) printf("Membox init success!\n"); } - /*申请内存块*/ + /* 申请内存块 */ mem = (UINT32 *)LOS_MemboxAlloc(boxMem); - if (NULL == mem) { + if (mem == NULL) { printf("Mem alloc failed!\n"); return; } printf("Mem alloc success!\n"); - /*赋值*/ - *mem = 828; + /* 内存地址读写验证 */ + *mem = MEMBOX_WR_TEST_NUM; printf("*mem = %d\n", *mem); - /*清除内存内容*/ + /* 清除内存内容 */ LOS_MemboxClr(boxMem, mem); - printf("Mem clear success \n *mem = %d\n", *mem); + printf("Mem clear success \n*mem = %d\n", *mem); - /*释放内存*/ + /* 释放内存 */ ret = LOS_MemboxFree(boxMem, mem); if (LOS_OK == ret) { printf("Mem free success!\n"); @@ -139,6 +144,7 @@ VOID Example_StaticMem(VOID) return; } + ``` @@ -146,7 +152,7 @@ VOID Example_StaticMem(VOID) 输出结果如下: - + ``` Membox init success! Mem alloc success! @@ -197,7 +203,7 @@ OpenHarmony LiteOS-M动态内存在TLSF算法的基础上,对区间的划分 2. 获取下一个内存区域的开始地址和长度,计算该内存区域和上一块内存区域的间隔大小gapSize。 -3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize+ OS_MEM_NODE_HEAD_SIZE。 +3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize + OS_MEM_NODE_HEAD_SIZE(即sizeof(struct OsMemUsedNodeHead))。 4. 把当前内存区域划分为一个空闲内存节点和一个尾节点,把空闲内存节点插入到空闲链表,并设置各个节点的前后链接关系。 @@ -218,14 +224,14 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 **表1** 动态内存模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 初始化和删除内存池 | - LOS_MemInit:初始化一块指定的动态内存池,大小为size。
- LOS_MemDeInit:删除指定内存池,仅打开LOSCFG_MEM_MUL_POOL时有效。 | -| 申请、释放动态内存 | - LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
- LOS_MemFree:释放从指定动态内存中申请的内存。
- LOS_MemRealloc:释放从指定动态内存中申请的内存。 | -| 获取内存池信息 | - LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
- LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
- LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
- LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开LOSCFG_MEM_MUL_POOL时有效。 | -| 获取内存块信息 | - LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
- LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | -| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | -| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | +| 初始化和删除内存池 |  LOS_MemInit:初始化一块指定的动态内存池,大小为size。
 LOS_MemDeInit:删除指定内存池,仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 | +| 申请、释放动态内存 |  LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
 LOS_MemFree:释放从指定动态内存中申请的内存。
 LOS_MemRealloc:释放从指定动态内存中申请的内存。 | +| 获取内存池信息 |  LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
 LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
 LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
 LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 | +| 获取内存块信息 |  LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
 LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | +| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开编译控制开关LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | +| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > - 由于动态内存管理需要管理控制块数据结构来管理内存,这些数据结构会额外消耗内存,故实际用户可使用内存总量小于配置项OS_SYS_MEM_SIZE的大小。 @@ -265,18 +271,24 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleDynMem。 + + ``` #include "los_memory.h" + #define TEST_POOL_SIZE (2*1024) -__attribute__((aligned(4))) UINT8 g_testPool[TEST_POOL_SIZE]; -VOID Example_DynMem(VOID) +#define MEMBOX_WR_TEST_NUM 828 + +__attribute__((aligned(4))) UINT8 g_testDynPool[TEST_POOL_SIZE]; + +VOID ExampleDynMem(VOID) { UINT32 *mem = NULL; UINT32 ret; - /*初始化内存池*/ - ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE); + /* 初始化内存池 */ + ret = LOS_MemInit(g_testDynPool, TEST_POOL_SIZE); if (LOS_OK == ret) { printf("Mem init success!\n"); } else { @@ -284,20 +296,20 @@ VOID Example_DynMem(VOID) return; } - /*分配内存*/ - mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4); - if (NULL == mem) { + /* 申请内存块 */ + mem = (UINT32 *)LOS_MemAlloc(g_testDynPool, 4); + if (mem == NULL) { printf("Mem alloc failed!\n"); return; } printf("Mem alloc success!\n"); - /*赋值*/ - *mem = 828; + /* 内存地址读写验证 */ + *mem = MEMBOX_WR_TEST_NUM; printf("*mem = %d\n", *mem); - /*释放内存*/ - ret = LOS_MemFree(g_testPool, mem); + /* 释放内存 */ + ret = LOS_MemFree(g_testDynPool, mem); if (LOS_OK == ret) { printf("Mem free success!\n"); } else { @@ -313,7 +325,7 @@ VOID Example_DynMem(VOID) 输出结果如下: - + ``` Mem init success! Mem alloc success! diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md b/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md index 01a3b8f011e35538fe15839b3c7b79cc017f3f53..7fddc4be0328b6c55b42c32e254d1ae242598f70 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md @@ -24,7 +24,7 @@ ## 运行机制 -软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置。 +软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置,该值按产品实际需要设定。 软件定时器使用了系统的一个队列和一个任务资源,软件定时器的触发遵循队列规则,先进先出。定时时间短的定时器总是比定时时间长的靠近队列头,满足优先被触发的准则。 @@ -64,11 +64,11 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 **表1** 软件定时器接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建、删除定时器 | - LOS_SwtmrCreate:创建定时器
- LOS_SwtmrDelete:删除定时器 | -| 启动、停止定时器 | - LOS_SwtmrStart:启动定时器
- LOS_SwtmrStop:停止定时器 | -| 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数 | +| 创建、删除定时器 | - LOS_SwtmrCreate:创建定时器。
- LOS_SwtmrDelete:删除定时器。 | +| 启动、停止定时器 | - LOS_SwtmrStart:启动定时器。
- LOS_SwtmrStop:停止定时器。 | +| 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数。 | ## 开发流程 @@ -130,86 +130,107 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 代码实现如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSwtmr。 + + ``` #include "los_swtmr.h" -/* Timer count */ -UINT32 g_timerCount1 = 0; -UINT32 g_timerCount2 = 0; +/* 定时器间隔时间 */ +#define SWTMR_INTERVAL_LONG 1000 +#define SWTMR_INTERVAL_SHORT 100 -/* 任务ID */ -UINT32 g_testTaskId01; +/* 定时器触发次数计数 */ +UINT32 g_timerCount1 = 0; +UINT32 g_timerCount2 = 0; -void Timer1_Callback(UINT32 arg) // 回调函数1 +/* 回调函数1,单次触发定时器的回调函数 */ +void Timer1Callback(UINT32 arg) { - UINT32 tick_last1; g_timerCount1++; - tick_last1 = (UINT32)LOS_TickCountGet(); // 获取当前Tick数 - printf("g_timerCount1=%d, tick_last1=%d\n", g_timerCount1, tick_last1); -} + printf("g_timerCount1=%d\n", g_timerCount1); +} -void Timer2_Callback(UINT32 arg) // 回调函数2 +/* 回调函数2,多次触发定时器的回调函数 */ +void Timer2Callback(UINT32 arg) { - UINT32 tick_last2; - tick_last2 = (UINT32)LOS_TickCountGet(); g_timerCount2++; - printf("g_timerCount2=%d tick_last2=%d\n", g_timerCount2, tick_last2); -} + printf("g_timerCount2=%d\n", g_timerCount2); +} -void Timer_example(void) +void SwtmrTest(void) { UINT32 ret; - UINT32 id1; // timer id1 - UINT32 id2; // timer id2 + UINT32 id1; // 定时器id1,单次触发定时器 + UINT32 id2; // 定时器id2,周期触发定时器 UINT32 tickCount; - /*创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ - LOS_SwtmrCreate(1000, LOS_SWTMR_MODE_ONCE, Timer1_Callback, &id1, 1); +#if (LOSCFG_BASE_CORE_SWTMR_ALIGN == 1) + /* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0, + OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE); - /*创建周期性软件定时器,每100Tick数执行回调函数2 */ - LOS_SwtmrCreate(100, LOS_SWTMR_MODE_PERIOD, Timer2_Callback, &id2, 1); - printf("create Timer1 success\n"); + /* 创建周期性软件定时器,每100Tick数执行回调函数2 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0, + OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE); +#else + /* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0); - LOS_SwtmrStart(id1); //启动单次软件定时器 - printf("start Timer1 success\n"); + /* 创建周期性软件定时器,每100Tick数执行回调函数2 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0); +#endif - LOS_TaskDelay(200); //延时200Tick数 - LOS_SwtmrTimeGet(id1, &tickCount); // 获得单次软件定时器剩余Tick数 - printf("tickCount=%d\n", tickCount); + /* 启动单次软件定时器 */ + ret = LOS_SwtmrStart(id1); + printf("start Timer1 %s\n", (ret == LOS_OK) ? "success" : "failed"); - LOS_SwtmrStop(id1); // 停止软件定时器 - printf("stop Timer1 success\n"); + /* 短时间延时,定时器还未触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_SHORT); + + /* 单次定时器还未到时间触发,此时停止应该成功 */ + ret = LOS_SwtmrStop(id1); + printf("stop timer1 %s\n", (ret == LOS_OK) ? "success" : "failed"); LOS_SwtmrStart(id1); - LOS_TaskDelay(1000); + + /* 长时间延时,定时器触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_LONG); + + /* 单次定时器触发后自删除,此时停止失败才是正常 */ + ret = LOS_SwtmrStop(id1); + printf("timer1 self delete test %s\n", (ret != LOS_OK) ? "success" : "failed"); + + /* 启动周期性软件定时器 */ + ret = LOS_SwtmrStart(id2); + printf("start Timer2 %s\n", (ret == LOS_OK) ? "success" : "failed"); - LOS_SwtmrStart(id2); // 启动周期性软件定时器 - printf("start Timer2\n"); + /* 长时间延时,定时器周期触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_LONG); - LOS_TaskDelay(1000); LOS_SwtmrStop(id2); - ret = LOS_SwtmrDelete(id2); // 删除软件定时器 + + ret = LOS_SwtmrDelete(id2); if (ret == LOS_OK) { printf("delete Timer2 success\n"); } } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleSwtmr(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; + TSK_INIT_PARAM_S taskParam = { 0 }; + UINT32 taskId; /* 锁任务调度 */ LOS_TaskLock(); - /* 创建任务1 */ - (VOID)memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Timer_example; - task1.pcName = "TimerTsk"; - task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + /* 创建任务 */ + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SwtmrTest; + taskParam.pcName = "TimerTsk"; + taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam.usTaskPrio = 5; + ret = LOS_TaskCreate(&taskId, &taskParam); if (ret != LOS_OK) { printf("TimerTsk create failed.\n"); return LOS_NOK; @@ -217,7 +238,6 @@ UINT32 Example_TaskEntry(VOID) /* 解锁任务调度 */ LOS_TaskUnlock(); - return LOS_OK; } ``` @@ -227,24 +247,22 @@ UINT32 Example_TaskEntry(VOID) 编译烧录运行,输出结果如下: - + ``` -create Timer1 success start Timer1 success -tickCount=798 -stop Timer1 success -g_timerCount1=1, tick_last1=1208 -delete Timer1 success -start Timer2 -g_timerCount2=1 tick_last2=1313 -g_timerCount2=2 tick_last2=1413 -g_timerCount2=3 tick_last2=1513 -g_timerCount2=4 tick_last2=1613 -g_timerCount2=5 tick_last2=1713 -g_timerCount2=6 tick_last2=1813 -g_timerCount2=7 tick_last2=1913 -g_timerCount2=8 tick_last2=2013 -g_timerCount2=9 tick_last2=2113 -g_timerCount2=10 tick_last2=2213 +stop timer1 success +g_timerCount1=1 +timer1 self delete test success +start Timer2 success +g_timerCount2=1 +g_timerCount2=2 +g_timerCount2=3 +g_timerCount2=4 +g_timerCount2=5 +g_timerCount2=6 +g_timerCount2=7 +g_timerCount2=8 +g_timerCount2=9 +g_timerCount2=10 delete Timer2 success ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-task.md b/zh-cn/device-dev/kernel/kernel-mini-basic-task.md index 50d320e915b4262a137e2cc89e92c7d387d79861..bf246040a71e2b7b17e049126e4339292c706f25 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-task.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-task.md @@ -3,7 +3,7 @@ ## 基本概念 -从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,并独立于其它任务运行。 +从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,各任务的运行相互独立。 OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任务间的切换,帮助用户管理业务程序流程。任务模块具有如下特性: @@ -40,7 +40,9 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 ![zh-cn_image_0000001200612002](figures/zh-cn_image_0000001200612002.png) -**任务状态迁移说明:** +系统会同时存在多个任务,因此就绪态和阻塞态的任务分别会加入就绪队列和阻塞队列。队列只是相同状态任务的合集,加入队列的先后与任务状态迁移的顺序无关。运行态任务仅存在一个,不存在运行态队列。 + +**任务状态迁移说明** - 就绪态→运行态 任务创建后进入就绪态,发生任务切换时,就绪队列中最高优先级的任务被执行,从而进入运行态,同时该任务从就绪队列中移出。 @@ -48,11 +50,11 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 - 运行态→阻塞态 正在运行的任务发生阻塞(挂起、延时、读信号量等)时,将该任务插入到对应的阻塞队列中,任务状态由运行态变成阻塞态,然后发生任务切换,运行就绪队列中最高优先级任务。 -- 阻塞态→就绪态(阻塞态→运行态) +- 阻塞态→就绪态(阻塞态→运行态的前置条件) 阻塞的任务被恢复后(任务恢复、延时时间超时、读信号量超时或读到信号量等),此时被恢复的任务会被加入就绪队列,从而由阻塞态变成就绪态;此时如果被恢复任务的优先级高于正在运行任务的优先级,则会发生任务切换,该任务由就绪态变成运行态。 - 就绪态→阻塞态 - 任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中删除,不会参与任务调度,直到该任务被恢复。 + 任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中移出,不会参与任务调度,直到该任务被恢复。 - 运行态→就绪态 有更高优先级任务创建或者恢复后,会发生任务调度,此刻就绪队列中最高优先级任务变为运行态,那么原先运行的任务由运行态变为就绪态,依然在就绪队列中。 @@ -65,7 +67,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 **任务ID** -任务ID,在任务创建时通过参数返回给用户,是任务的重要标识。系统中的ID号是唯一的。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。 +在任务创建时通过参数返回给用户。系统中任务ID号是唯一的,是任务的重要标识。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。 **任务优先级** @@ -83,7 +85,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 任务在运行过程中使用的一些资源,如寄存器等,称为任务上下文。当这个任务挂起时,其他任务继续执行,可能会修改寄存器等资源中的值。如果任务切换时没有保存任务上下文,可能会导致任务恢复后出现未知错误。因此在任务切换时会将切出任务的任务上下文信息,保存在自身的任务栈中,以便任务恢复后,从栈空间中恢复挂起时的上下文信息,从而继续执行挂起时被打断的代码。 -**任务控制块TCB** +**任务控制块(TCB)** 每个任务都含有一个任务控制块(TCB)。TCB包含了任务上下文栈指针(stack pointer)、任务状态、任务优先级、任务ID、任务名、任务栈大小等信息。TCB可以反映出每个任务运行情况。 @@ -103,15 +105,14 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 **表1** 任务管理模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskDelete:删除指定的任务。 | -| 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。
LOS_TaskSuspend:挂起指定的任务,然后切换任务。
LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源
LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。
LOS_Msleep:传入参数为毫秒数,转换为Tick数目,调用LOS_TaskDelay。
LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 | -| 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。
LOS_TaskUnlock:解锁任务调度。
LOS_Schedule:触发任务调度。 | -| 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。
LOS_TaskPriSet:设置指定任务的优先级。
LOS_TaskPriGet:获取指定任务的优先级。 | -| 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。
LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。
LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。
LOS_CurTaskNameGet:获取当前任务的名称。
LOS_TaskNameGet:获取指定任务的名称。
LOS_TaskStatusGet:获取指定任务的状态。
LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。
LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 | -| 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启宏LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 | - +| 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入suspend状态。
LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskDelete:删除指定的任务。 | +| 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。
LOS_TaskSuspend:挂起指定的任务,然后切换任务。
LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源
LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。
LOS_Msleep:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为毫秒数。
LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 | +| 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。
LOS_TaskUnlock:解锁任务调度。
LOS_Schedule:触发任务调度。 | +| 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。
LOS_TaskPriSet:设置指定任务的优先级。
LOS_TaskPriGet:获取指定任务的优先级。 | +| 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。
LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。
LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。
LOS_CurTaskNameGet:获取当前任务的名称。
LOS_TaskNameGet:获取指定任务的名称。
LOS_TaskStatusGet:获取指定任务的状态。
LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。
LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 | +| 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启编译控制宏:LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 | ## 开发流程 @@ -161,20 +162,24 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 本实例介绍基本的任务操作方法,包含2个不同优先级任务的创建、任务延时、任务锁与解锁调度、挂起和恢复等操作,阐述任务优先级调度的机制以及各接口的应用。示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTask。 + + ``` +#include "los_task.h" + UINT32 g_taskHiId; UINT32 g_taskLoId; -#define TSK_PRIOR_HI 4 -#define TSK_PRIOR_LO 5 +#define TSK_PRIOR_HI 3 /* 高优先级任务的优先级 */ +#define TSK_PRIOR_LO 4 /* 低优先级任务的优先级 */ -UINT32 Example_TaskHi(VOID) +UINT32 ExampleTaskHi(VOID) { UINT32 ret; printf("Enter TaskHi Handler.\n"); - /* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(TaskLo任务) */ + /* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(即TaskLo任务) */ ret = LOS_TaskDelay(100); if (ret != LOS_OK) { printf("Delay TaskHi Failed.\n"); @@ -195,7 +200,7 @@ UINT32 Example_TaskHi(VOID) } /* 低优先级任务入口函数 */ -UINT32 Example_TaskLo(VOID) +UINT32 ExampleTaskLo(VOID) { UINT32 ret; @@ -220,24 +225,25 @@ UINT32 Example_TaskLo(VOID) } /* 任务测试入口函数,创建两个不同优先级的任务 */ -UINT32 Example_TskCaseEntry(VOID) +UINT32 ExampleTask(VOID) { UINT32 ret; - TSK_INIT_PARAM_S initParam; + TSK_INIT_PARAM_S taskParam1 = { 0 }; + TSK_INIT_PARAM_S taskParam2 = { 0 }; /* 锁任务调度,防止新创建的任务比本任务高而发生调度 */ LOS_TaskLock(); printf("LOS_TaskLock() Success!\n"); - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskHi; - initParam.usTaskPrio = TSK_PRIOR_HI; - initParam.pcName = "TaskHi"; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - initParam.uwResved = 0; /* detach 属性 */ + taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi; + taskParam1.usTaskPrio = TSK_PRIOR_HI; + taskParam1.pcName = "TaskHi"; + taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam1.uwResved = LOS_TASK_ATTR_JOINABLE; /* detach 属性 */ /* 创建高优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ - ret = LOS_TaskCreate(&g_taskHiId, &initParam); + ret = LOS_TaskCreate(&g_taskHiId, &taskParam1); if (ret != LOS_OK) { LOS_TaskUnlock(); @@ -247,13 +253,13 @@ UINT32 Example_TskCaseEntry(VOID) printf("Example_TaskHi create Success!\n"); - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskLo; - initParam.usTaskPrio = TSK_PRIOR_LO; - initParam.pcName = "TaskLo"; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo; + taskParam2.usTaskPrio = TSK_PRIOR_LO; + taskParam2.pcName = "TaskLo"; + taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; /* 创建低优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ - ret = LOS_TaskCreate(&g_taskLoId, &initParam); + ret = LOS_TaskCreate(&g_taskLoId, &taskParam2); if (ret != LOS_OK) { LOS_TaskUnlock(); printf("Example_TaskLo create Failed!\n"); @@ -266,7 +272,7 @@ UINT32 Example_TskCaseEntry(VOID) LOS_TaskUnlock(); ret = LOS_TaskJoin(g_taskHiId, NULL); if (ret != LOS_OK) { - printf("Join Example_TaskHi Failed!\n"); + printf("Join Example_TaskHi Failed!, 0x%x\n", ret); } else { printf("Join Example_TaskHi Success!\n"); } @@ -279,8 +285,8 @@ UINT32 Example_TskCaseEntry(VOID) 编译运行得到的结果为: - -``` + +``` LOS_TaskLock() Success! Example_TaskHi create Success! Example_TaskLo create Success! diff --git a/zh-cn/device-dev/kernel/kernel-basic-mini-time.md b/zh-cn/device-dev/kernel/kernel-mini-basic-time.md similarity index 60% rename from zh-cn/device-dev/kernel/kernel-basic-mini-time.md rename to zh-cn/device-dev/kernel/kernel-mini-basic-time.md index 36c468a90bca1d1a37daaaf698647b7454f5d29c..6e96095c08f3e74684d226fc6e7c23fe655cf997 100644 --- a/zh-cn/device-dev/kernel/kernel-basic-mini-time.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-time.md @@ -29,8 +29,8 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 | 接口名 | 描述 | | -------- | -------- | -| LOS_MS2Tick | 毫秒转换成Tick | -| LOS_Tick2MS | Tick转化为毫秒 | +| LOS_MS2Tick | 毫秒转换成Tick。 | +| LOS_Tick2MS | Tick转化为毫秒。 | | OsCpuTick2MS | Cycle数目转化为毫秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | | OsCpuTick2US | Cycle数目转化为微秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | @@ -38,10 +38,23 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 | 接口名 | 描述 | | -------- | -------- | -| LOS_SysClockGet | 获取系统时钟 | -| LOS_TickCountGet | 获取自系统启动以来的Tick数 | -| LOS_CyclePerTickGet | 获取每个Tick多少Cycle数 | +| LOS_SysClockGet | 获取系统时钟。 | +| LOS_TickCountGet | 获取自系统启动以来的Tick数。 | +| LOS_CyclePerTickGet | 获取每个Tick多少Cycle数。 | +| LOS_CurrNanosec | 获取当前的时间,单位纳秒。 | + **表3** 时间注册 + +| 接口名 | 描述 | +| --------------------- | ---------------------------------------------- | +| LOS_TickTimerRegister | 重新注册系统时钟的定时器和对应的中断处理函数。 | + + **表4** 延时 + +| 接口名 | 描述 | +| ---------- | ------------------------ | +| LOS_MDelay | 延时函数,延时单位毫秒。 | +| LOS_UDelay | 延时函数,延时单位微秒。 | ## 开发流程 @@ -56,7 +69,7 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 > > - 系统的Tick数在关中断的情况下不进行计数,故系统Tick数不能作为准确时间使用。 > -> - 配置选项维护在开发板工程的文件target_config.h。 +> - 上文描述的配置选项维护在开发板工程 target_config.h 中,部分配置项未定义的缺省值定义在内核 los_config.h中。 ## 编程实例 @@ -81,17 +94,22 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 时间转换: +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTransformTime和ExampleGetTime。 + ``` -VOID Example_TransformTime(VOID) +VOID ExampleTransformTime(VOID) { UINT32 ms; UINT32 tick; - tick = LOS_MS2Tick(10000); // 10000ms转换为tick - dprintf("tick = %d \n", tick); - ms = LOS_Tick2MS(100); // 100tick转换为ms - dprintf("ms = %d \n", ms); + /* 10000ms转换为tick */ + tick = LOS_MS2Tick(10000); + printf("tick = %d \n", tick); + + /* 100tick转换为ms */ + ms = LOS_Tick2MS(100); + printf("ms = %d \n", ms); } ``` @@ -99,26 +117,21 @@ VOID Example_TransformTime(VOID) ``` -VOID Example_GetTime(VOID) +VOID ExampleGetTime(VOID) { UINT32 cyclePerTick; - UINT64 tickCount; + UINT64 tickCountBefore; + UINT64 tickCountAfter; cyclePerTick = LOS_CyclePerTickGet(); - if(0 != cyclePerTick) { - dprintf("LOS_CyclePerTickGet = %d \n", cyclePerTick); - } - - tickCount = LOS_TickCountGet(); - if(0 != tickCount) { - dprintf("LOS_TickCountGet = %d \n", (UINT32)tickCount); + if (0 != cyclePerTick) { + printf("LOS_CyclePerTickGet = %d \n", cyclePerTick); } + tickCountBefore = LOS_TickCountGet(); LOS_TaskDelay(200); - tickCount = LOS_TickCountGet(); - if(0 != tickCount) { - dprintf("LOS_TickCountGet after delay = %d \n", (UINT32)tickCount); - } + tickCountAfter = LOS_TickCountGet(); + printf("LOS_TickCountGet after delay rising = %d \n", (UINT32)(tickCountAfter - tickCountBefore)); } ``` @@ -138,8 +151,7 @@ ms = 1000 时间统计和时间延迟: -``` -LOS_CyclePerTickGet = 495000 -LOS_TickCountGet = 1 -LOS_TickCountGet after delay = 201 +``` +LOS_CyclePerTickGet = 250000 (根据实际运行环境,数据会有差异) +LOS_TickCountGet after delay rising = 200 ``` diff --git a/zh-cn/device-dev/kernel/kernel-standard-build.md b/zh-cn/device-dev/kernel/kernel-standard-build.md index 04b56ca1c61a6d45f057bf820000ae2935f47342..20eef2cb8b7ab98a92ec597fa797f62a1f9cfd69 100644 --- a/zh-cn/device-dev/kernel/kernel-standard-build.md +++ b/zh-cn/device-dev/kernel/kernel-standard-build.md @@ -9,7 +9,7 @@ 使用工程的全量编译命令,编译生成uImage内核镜像 -``` +```bash ./build.sh --product-name hispark_taurus_standard # 编译hispark_taurus_standard镜像 --build-target build_kernel # 编译hispark_taurus_standard的uImage内核镜像 --gn-args linux_kernel_version=\"linux-5.10\" # 编译指定内核版本 diff --git a/zh-cn/device-dev/kernel/kernel-standard-mm-eswap.md b/zh-cn/device-dev/kernel/kernel-standard-mm-eswap.md index 86dd9b65fd9e24e34a9e3d1a4886714b3b0146e6..620ae2bbcbf112726e42ee32ffd6485465422e1a 100644 --- a/zh-cn/device-dev/kernel/kernel-standard-mm-eswap.md +++ b/zh-cn/device-dev/kernel/kernel-standard-mm-eswap.md @@ -8,24 +8,27 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ## ZRAM与ESwap配置指导 +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 使能ESwap需要在使能ZRAM之前,不需要使用ESwap时, 也可以仅使能ZRAM。如部分设备不包括用于换出的存储设备,也没有新建相应的存储分区,那么可以仅使能ZRAM来通过zswapd进行内存回收。 + ### 使能ESwap 1. 打开相关配置项及依赖 启用ESwap,需要通过编译内核时打开相应的配置项及依赖,ESwap相关CONFIG如下: ``` - CONFIG_HYPERHOLD=y - CONFIG_HYPERHOLD_DEBUG=y - CONFIG_HYPERHOLD_ZSWAPD=y - CONFIG_HYPERHOLD_FILE_LRU=y - CONFIG_HYPERHOLD_MEMCG=y - CONFIG_ZRAM_GROUP=y - CONFIG_ZRAM_GROUP_DEBUG=y - CONFIG_ZLIST_DEBUG=y - CONFIG_ZRAM_GROUP_WRITEBACK=y + CONFIG_HYPERHOLD=y // Enable HyperHold + CONFIG_HYPERHOLD_DEBUG=y // Enable HyperHold Debug + CONFIG_HYPERHOLD_ZSWAPD=y // Enable zswapd thread to reclaim anon pages in background + CONFIG_HYPERHOLD_FILE_LRU=y // Enable HyperHold FILE LRU + CONFIG_HYPERHOLD_MEMCG=y // Enable Memcg Management in HyperHold + CONFIG_ZRAM_GROUP=y // Enable Manage Zram objs with mem_cgroup + CONFIG_ZRAM_GROUP_DEBUG=y // Enable Manage Zram objs with mem_cgroup Debug + CONFIG_ZLIST_DEBUG=y // Enable Debug info for zram group list + CONFIG_ZRAM_GROUP_WRITEBACK=y // Enable Write back grouped zram objs to Hyperhold driver ``` - 另有部分CONFIG被依赖: + 同时,开启ESwap需依赖以下CONFIG: ``` CONFIG_MEMCG=y @@ -72,9 +75,6 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 使能ESwap需要在使能ZRAM之前,不需要使用ESwap时, 也可以仅使能ZRAM。如部分设备不包括用于换出的存储设备,也没有新建相应的存储分区,那么可以仅使能ZRAM来通过zswapd进行内存回收。 - ### 使能ZRAM 1. 初始化ZRAM @@ -91,7 +91,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > /sys/block/zram0/group可接受参数及作用为: > - > - disable:表示disable; + > - disable:表示禁用; > - readonly:表示只记录数据的cgroup信息,并不换出; > - readwrite:表示打开ZRAM到eswap的换入换出功能。 @@ -134,34 +134,33 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ESwap提供了一些接口用于控制换入换出策略以及记录当前状态,这些接口位于memcg所挂载的目录当中,如`/dev/memcg/`。 -| 功能分类 | 接口名 | 描述 | -| -------- | -------- | -------- | -| 控制接口 | [avail_buffers](#avail_buffers) | 设置buffer区间 | -| | [zswapd_single_memcg_param](#zswapd_single_memcg_param) | 设置当前memcg相关配置 | -| | [zram_wm_ratio](#zram_wm_ratio) | 设置zram换出水线 | -| 状态接口 | [zswapd_pressure_show](#zswapd_pressure_show) | 记录当前buffer以及refault | -| | [stat](#stat) | 检测ESwap实时情况 | -| | [zswapd_vmstat_show](#zswapd_vmstat_show) | 记录zswapd运行过程中各种事件 | +| 功能分类 | 接口名 | 描述 | 参考值 | +| -------- | -------- | -------- | -------- | +| 控制接口 | [avail_buffers](#avail_buffers) | 设置buffer区间 | 300 250 350 200 | +| | [zswapd_single_memcg_param](#zswapd_single_memcg_param) | 设置当前memcg相关配置 | 300 40 0 0 | +| | [zram_wm_ratio](#zram_wm_ratio) | 设置zram换出水线 | 0 | +| 状态接口 | [zswapd_pressure_show](#zswapd_pressure_show) | 记录当前buffer以及refault | NA | +| | [stat](#stat) | 检测ESwap实时情况 | NA | +| | [zswapd_vmstat_show](#zswapd_vmstat_show) | 记录zswapd运行过程中各种事件 | NA | > ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:** > 除avail_buffers会因为调整了buffer水线而会主动去唤醒zswapd外,其余控制接口并不会主动唤醒zswapd,只是其配置需在zswapd所被唤醒后方可生效。 -各接口的具体描述如下: ### avail_buffers -avail_buffers接口用于设置buffer区间[min_avail_buffers, high_avail_buffers],当检测到当前的buffer低于min_avail_buffers时则会唤醒zswapd进行匿名页回收,期望的回收量为high_avail_buffers与当前系统buffer值的差值,实际可能会因为无法回收等原因而未回收那么多内存。avail_buffers为期望的内存正常状态buffer值,free_swap_threshold则是设置交换分区空闲容量的阈值,当zswapd唤醒并进行内存回收之后,会根据当前系统情况以及两者的设置记录当前内存压力事件,如medium press,critical press等。可主动调整来触发zswapd回收,如`echo 1000 950 1050 0 > /dev/memcg/memory.avail_buffers`。 +avail_buffers接口用于设置buffer区间[min_avail_buffers, high_avail_buffers],当检测到当前的buffer低于min_avail_buffers时则会唤醒zswapd进行匿名页回收,期望的回收量为high_avail_buffers与当前系统buffer值的差值,实际可能会因为无法回收等原因而未回收足够多内存。avail_buffers为期望的内存正常状态buffer值,free_swap_threshold则是设置交换分区空闲容量的阈值,当zswapd唤醒并进行内存回收之后,会根据当前系统情况以及两者的设置记录当前内存压力事件,如medium press,critical press等。可主动调整来触发zswapd回收,如`echo 1000 950 1050 0 > /dev/memcg/memory.avail_buffers`。 -默认值: +**默认值:** ``` - avail_buffers: 0 - min_avail_buffers: 0 - high_avail_buffers: 0 - free_swap_threshold: 0 +avail_buffers: 0 +min_avail_buffers: 0 +high_avail_buffers: 0 +free_swap_threshold: 0 ``` -限制: +**限制:** 0<=min_avail_buffers<=avail_buffers<=high_avail_buffers @@ -176,10 +175,10 @@ avail_buffers接口用于设置buffer区间[min_avail_buffers, high_avail_buffer 默认值: ``` - memcg score: 300 - memcg ub_mem2zram_ratio: 60 - memcg ub_zram2ufs_ratio: 10 - memcg refault_threshold: 50 +memcg score: 300 +memcg ub_mem2zram_ratio: 60 +memcg ub_zram2ufs_ratio: 10 +memcg refault_threshold: 50 ``` 限制: @@ -196,13 +195,13 @@ avail_buffers接口用于设置buffer区间[min_avail_buffers, high_avail_buffer 设置ZRAM换出水线,即当当前ZRAM中压缩的匿名页大于ZRAM总大小*zram_wm_ratio时,会开始向ESwap进行换出,但是具体换出时间为zswapd因buffer水线而唤醒之后。设置为0时系统默认为37,可进行调整,如`echo 30 > /dev/memcg/memory.zram_wm_ratio`。 -默认值: +**默认值:** ``` - zram_wm_ratio: 0 +zram_wm_ratio: 0 ``` -限制: +**限制:** 0<=zram_wm_ratio<=100 @@ -225,7 +224,7 @@ avail_buffers接口用于设置buffer区间[min_avail_buffers, high_avail_buffer ## 触发zswapd回收 -可先通过`cat /dev/memcg/memory.zswapd_pressure_show`查看当前buffer值,比如当前为1200,那么便可通过主动调整buffer区间,来主动唤醒zswapd。 +可先通过`cat /dev/memcg/memory.zswapd_pressure_show`查看当前buffer值,比如当前为1200,那么可通过主动调整buffer区间大于1200,来主动唤醒zswapd。 ```Bash echo 1300 1250 1350 0 > /dev/memcg/memory.avail_buffers @@ -234,7 +233,4 @@ echo 1300 1250 1350 0 > /dev/memcg/memory.avail_buffers ## ESwap配置大小示例 -ZRAM与ESwap的大小配置需根据实际使用场景以及产品硬件特点进行适配。目前在rk3568板子上使用时,其ram为2G,因此设置的ZRAM与ESwap大小均为512MB。 - - - +ZRAM与ESwap的大小配置需根据实际使用场景以及产品硬件特点进行适配。目前在rk3568板子上使用时,其ram为2G,因此设置的ZRAM与ESwap大小均为512MB。 \ No newline at end of file diff --git a/zh-cn/device-dev/kernel/kernel-standard-newip.md b/zh-cn/device-dev/kernel/kernel-standard-newip.md index c507257656f86fa1c9dcd862e22ba78ae9433940..caf9c0bb4cd638c0dbf5346d7559a71814c530ec 100644 --- a/zh-cn/device-dev/kernel/kernel-standard-newip.md +++ b/zh-cn/device-dev/kernel/kernel-standard-newip.md @@ -32,10 +32,6 @@ NewIP WiFi灵活极简报文头如下图所示,通过LLC Header中的EtherType ![zh-cn_image-20220915140627223](figures/zh-cn_image-20220915140627223.png) -NewIP Eth灵活极简报文头如下图所示,通过Eth头中的EtherType = 0xEADD标识NewIP灵活极简报文。 - -![zh-cn_image-20220930113757464](figures/zh-cn_image-20220930113757464.png) - 1) Dispatch:指示封装子类,数值0b0表示其为极简封装子类,长度为1比特;(0b表示后面数值为二进制)。 2) Bitmap:变长,Bitmap默认为紧跟在Dispatch有效位后面的7比特,Bitmap字段长度可持续扩展。Bitmap最后一位置0表示Bitmap结束,最后一位置1表示Bitmap向后扩展1 Byte,直至最后一位置0。 @@ -250,11 +246,11 @@ struct sockaddr_nin { ## NewIP开发说明 -目前只在OpenHarmony Linux-5.10内核支持NewIP内核协议栈,只能在用户态人工配置NewIP地址和路由到内核,两台设备可以通过路由器WiFi连接,也可以通过Eth网线直接连接。如果想配置NewIP地址和路由后自动切换到NewIP内核协议栈通信,应用可以参考下面蓝框中描述。 +目前只在OpenHarmony Linux-5.10内核支持NewIP内核协议栈,只能在用户态人工配置NewIP地址和路由到内核,两台设备通过路由器WiFi连接。如果想配置NewIP地址和路由后自动切换到NewIP内核协议栈通信,应用可以参考下面蓝框中描述。 ![zh-cn_image-20221009112548444](figures/zh-cn_image-20221009112548444.png) -上图中NewIP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony-sig/communication_sfc_newip/tree/master/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置NewIP地址和路由。 +上图中NewIP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony/communication_sfc_newip/tree/master/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置NewIP地址和路由。 | 文件名 | 功能 | | ------------------ | ------------------------------------------------------ | @@ -284,7 +280,7 @@ struct sockaddr_nin { ## NewIP收发包代码示例 -NewIP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,NewIP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony-sig/communication_sfc_newip/tree/master/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。 +NewIP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,NewIP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony/communication_sfc_newip/tree/master/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。 | 文件名 | 功能 | | --------------------- | ----------------------------- | @@ -304,7 +300,7 @@ NewIP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如 2. 将编译生成二级制文件上传到设备1,设备2。 -3. 执行“ifconfig xxx up”开启网卡设备,xxx表示网卡名,比如eth0,wlan0。 +3. 执行“ifconfig wlan0 up”开启网卡设备。 4. 在设备1的sh下执行“./nip_addr_cfg_demo server”给服务端配置0xDE00(2字节)变长地址,在设备2的sh下执。行“./nip_addr_cfg_demo client”给客户端配置0x50(1字节)变长地址,通过“cat /proc/net/nip_addr”查看内核地址配置结果。 @@ -383,7 +379,7 @@ allowxperm thread_xxx thread_xxx:socket ioctl { 0x8933 0x8916 0x890B }; ## WireShark报文解析模板 -Wireshark默认报文解析规则无法解析NewIP报文,在WireShark配置中添加NewIP报文解析模板可以实现NewIP报文解析,[NewIP报文解析模板](https://gitee.com/openharmony-sig/communication_sfc_newip/blob/master/tools/wireshark_cfg_for_newip.lua)详见代码仓。 +Wireshark默认报文解析规则无法解析NewIP报文,在WireShark配置中添加NewIP报文解析模板可以实现NewIP报文解析,[NewIP报文解析模板](https://gitee.com/openharmony/communication_sfc_newip/blob/master/tools/wireshark_cfg_for_newip.lua)详见代码仓。 报文解析模板配置文件的方法: diff --git a/zh-cn/device-dev/kernel/kernel-standard-overview.md b/zh-cn/device-dev/kernel/kernel-standard-overview.md index 50361707d3a089c30884301b249f11c9fcc10044..a93ab7971c893bf464ba839e6609de15ee3e3f55 100644 --- a/zh-cn/device-dev/kernel/kernel-standard-overview.md +++ b/zh-cn/device-dev/kernel/kernel-standard-overview.md @@ -1,16 +1,16 @@ # Linux内核概述 -标准系统类设备(参考内存≥128MiB),OpenHarmony选择Linux内核作为基础内核,可以对不同资源受限的设备产品配置出适合的OS内核,为上层提供基础的操作系统能力。 +标准系统类设备是面向应用处理器的设备,支持的设备最小内存为128MiB。OpenHarmony选择Linux内核作为基础内核,可以对不同资源受限的设备产品配置出适合的OS内核,为上层提供基础的操作系统能力。 ## Linux内核版本 -Linux内核版本分为稳定版本以及长期支持LTS(long term support)版本。 +- Linux内核版本分为稳定版本以及长期支持LTS(long term support)版本。 -稳定版本大约每三个月发布一个新版本,包含最新硬件支持、性能改进以及bug修复等。其缺点是整体维护生命周期较短,产品软件不能得到长期稳定的支持。 +- 稳定版本大约每三个月发布一个新版本,包含最新硬件支持、性能改进以及bug修复等。其缺点是整体维护生命周期较短,产品软件不能得到长期稳定的支持。 -LTS为长期支持版本,“长期支持”体现在对该版本内核的长期维护(对bug和安全方面的修复),一般维护周期达到6年之久。相较于维护周期从6个月到2年不等非LTS内核版本,对一款商用产品来说并不能覆盖其产品完整的生命周期,很有可能会使产品暴露于安全漏洞的风险之中。且LTS版本更新不会包含新的特性升级,保证了版本的稳定,这对追求稳定以及安全的商用产品来说LTS版本更为适合。 +- LTS为长期支持版本,“长期支持”体现在对该版本内核的长期维护(对bug和安全方面的修复),一般维护周期达到6年之久。相较于维护周期从6个月到2年不等非LTS内核版本,对一款商用产品来说并不能覆盖其产品完整的生命周期,很有可能会使产品暴露于安全漏洞的风险之中。且LTS版本更新不会包含新的特性升级,保证了版本的稳定,这对追求稳定以及安全的商用产品来说LTS版本更为适合。 ## OpenHarmony内核版本选择 diff --git a/zh-cn/device-dev/kernel/kernel-standard-patch.md b/zh-cn/device-dev/kernel/kernel-standard-patch.md index 71d41ca8257764b8a3cd43801511ffe7e10ff840..d4f3820f26cc4c000bc747199d5ece4e7cafbd54 100644 --- a/zh-cn/device-dev/kernel/kernel-standard-patch.md +++ b/zh-cn/device-dev/kernel/kernel-standard-patch.md @@ -1,23 +1,21 @@ # OpenHarmony开发板Patch使用指导 -1. 合入HDF补丁 - 在kernel/linux/build仓中,按照kernel.mk中HDF的补丁合入方法,合入不同内核版本对应的HDF内核补丁: - ``` +1. 合入HDF补丁。 + 按照[kernel.mk](https://gitee.com/openharmony/kernel_linux_build/blob/master/kernel.mk)中HDF的补丁合入方法,合入不同内核版本对应的HDF内核补丁: + ```makefile $(OHOS_BUILD_HOME)/drivers/hdf_core/adapter/khdf/linux/patch_hdf.sh $(OHOS_BUILD_HOME) $(KERNEL_SRC_TMP_PATH) $(KERNEL_PATCH_PATH) $(DEVICE_NAME) ``` -2. 合入芯片平台驱动补丁 - 以Hi3516DV300为例: - - 在kernel/linux/build仓中,按照kernel.mk中的芯片组件所对应的patch路径规则及命名规则,将对应的芯片组件patch放到对应路径下: - ``` +2. 合入芯片平台驱动补丁,以Hi3516DV300为例。 + 按照[kernel.mk](https://gitee.com/openharmony/kernel_linux_build/blob/master/kernel.mk)中的芯片组件所对应的patch路径规则及命名规则,将对应的芯片组件patch放到对应路径下: + ```makefile DEVICE_PATCH_DIR := $(OHOS_BUILD_HOME)/kernel/linux/patches/${KERNEL_VERSION}/$(DEVICE_NAME)_patch DEVICE_PATCH_FILE := $(DEVICE_PATCH_DIR)/$(DEVICE_NAME).patch ``` -3. 修改自己所需要编译的config - 在kernel/linux/build仓中,按照kernel.mk中的芯片组件所对应的patch路径规则及命名规则,将对应的芯片组件config放到对应路径下: - ``` +3. 修改自己所需要编译的config。 + 按照[kernel.mk](https://gitee.com/openharmony/kernel_linux_build/blob/master/kernel.mk)中的芯片组件所对应的patch路径规则及命名规则,将对应的芯片组件config放到对应路径下: + ```makefile KERNEL_CONFIG_PATH := $(OHOS_BUILD_HOME)/kernel/linux/config/${KERNEL_VERSION} DEFCONFIG_FILE := $(DEVICE_NAME)_$(BUILD_TYPE)_defconfig ``` @@ -25,4 +23,4 @@ > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:** > 由于OpenHarmony工程的编译构建流程中会拷贝kernel/linux/linux-\*.\*的代码环境后进行打补丁动作,在使用OpenHarmony的版本级编译命令前,需要kernel/linux/linux-\*.\*原代码环境。 > - > 根据不同系统工程,编译完成后会在out目录下的kernel目录中生成对应实际编译的内核,基于此目录的内核,进行对应的config修改,将最后生成的.config文件cp到config仓对应的路径文件里,即可生效。 + > 根据不同系统工程,编译完成后会在out目录下的kernel目录中生成对应实际编译的内核,基于此目录的内核,进行对应平台的config修改,将最后生成的.config文件cp到config仓对应平台的路径文件里,即可生效。 diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-audio-03.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-audio-03.png new file mode 100644 index 0000000000000000000000000000000000000000..248ea1854492ca3d2c02fb5a1be1fd5d4ef408a8 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-audio-03.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-01.png new file mode 100644 index 0000000000000000000000000000000000000000..6be451aec844699dc7d254de5c48ce08507a8431 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-02.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-02.png new file mode 100644 index 0000000000000000000000000000000000000000..062598d4095dbbd7b41c460aa1b09634a3bcb1b2 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-02.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-bt-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-bt-01.png new file mode 100644 index 0000000000000000000000000000000000000000..2bf182464e58219294cb38f36ed652c6391ff2a8 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-bt-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-camera-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-camera-01.png new file mode 100644 index 0000000000000000000000000000000000000000..1a4fa27e98e5bb4568be1399b57da3b987ee4fbf Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-camera-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-sensor-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-sensor-01.png new file mode 100644 index 0000000000000000000000000000000000000000..3fae6a7aa94e445668e0dd80a1374a04e607f24e Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-sensor-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-01.png new file mode 100644 index 0000000000000000000000000000000000000000..83884ab97b8cf678c466da4d1cd71b116d1199a1 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-02.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-02.png new file mode 100644 index 0000000000000000000000000000000000000000..a9d5ec775f67a0775c38532455d91f3a5b616e58 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-02.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-vibrator-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-vibrator-01.png new file mode 100644 index 0000000000000000000000000000000000000000..5527ef2a4b3887eb51a9c9e340a107da5535a425 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-vibrator-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-02.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-02.png new file mode 100644 index 0000000000000000000000000000000000000000..d150f2aa9c744fdf9ce144ce614be99c88587059 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-02.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-03.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-03.png new file mode 100644 index 0000000000000000000000000000000000000000..24f64af806b6e0f5acb1006a22966bd79d3a8a49 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-03.png differ diff --git a/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md b/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md index 525055339c5e23b7d5d1290ca13a1a0893520ed1..49a9a80a4852e2975095672f55e898fb2ba0ca8b 100755 --- a/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md +++ b/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md @@ -1,6 +1,6 @@ -**标准系统方案之瑞芯微RK3568移植案例** +# 标准系统方案之瑞芯微RK3568移植案例 -​ 本文章是基于瑞芯微RK3568芯片的DAYU200开发板,进行标准系统相关功能的移植,主要包括产品配置添加,内核启动、升级,音频ADM化,Camera,TP,LCD,WIFI,BT,vibrator、sensor、图形显示模块的适配案例总结,以及相关功能的适配。 +​本文章是基于瑞芯微RK3568芯片的DAYU200开发板,进行标准系统相关功能的移植,主要包括产品配置添加,内核启动、升级,音频ADM化,Camera,TP,LCD,WIFI,BT,vibrator、sensor、图形显示模块的适配案例总结,以及相关功能的适配。 ## 产品配置和目录规划 @@ -212,7 +212,7 @@ init相关配置请参考[启动子系统的规范要求](https://gitee.com/open ADM结构框图如下,Audio Peripheral Drivers和Platform Drivers为平台适配需要完成的工作。 -dayu200-audio-03.png +![dayu200-audio-03.png](figures/dayu200/dayu200-audio-03.png) 结合第1步梳理出来的Audio结构分析,Audio Peripheral Drivers包含Rk809的驱动,Platform Drivers包含DMA驱动和I2S驱动。 @@ -1085,7 +1085,7 @@ product.gni中指定了chipset_build_deps camera_device_manager_deps 和 camera_ #### 框架适配介绍 -​ img + ![dayu200-camera-01.png](figures/dayu200/dayu200-camera-01.png) ​ 以V4l2为例,pipeline的连接方式是在HCS配置文件中配置连接,数据源我们称之为SourceNode,主要包括硬件设备的控制、数据流的轮转等。 @@ -1883,7 +1883,8 @@ struct v4l2_buffer { - InputController:提供input设备的业务控制接口,包括获取器件信息及设备类型、设置电源状态等。 **图 1** INPUT模块HDI接口层框架图 -dayu200-tp-01.png + +![dayu200-tp-01.png](figures/dayu200/dayu200-tp-01.png) 相关目录下源代码目录结构如下所示 @@ -1922,7 +1923,7 @@ tp驱动的适配依赖hdf的input模型,hdf的input模型提供了TP,KEY, 从功能的角度看hdf input模块的框架如下: -tp +![dayu200-tp-02.png](figures/dayu200/dayu200-tp-02.png) 因为hdf input模型的高度抽象集成,TP驱动的适配驱动主要涉及器件驱动层的适配。 @@ -2294,7 +2295,7 @@ device4 :: deviceNode { 基于HDF框架开发的 背光驱动模型 - +![dayu200-backlight-01.png](figures/dayu200/dayu200-backlight-01.png) rk3568背光是通过pwm控制占空比实现的,具体使用的是pwm4 @@ -2398,7 +2399,7 @@ static struct BacklightOps g_blDevOps = { 其实使用的就是HDF PWM 实现的对接内核pwm的接口 - +![dayu200-backlight-02.png](figures/dayu200/dayu200-backlight-02.png) 在LCD HDF器件驱动注册背光 @@ -2493,7 +2494,7 @@ HDF WiFi框架总体框架图 #### 驱动模块初始化流程分析 -dayu200-wifi-02.png +![dayu200-wifi-02.png](figures/dayu200/dayu200-wifi-02.png) Ap6275s 是一款SDIO设备WiFi模组驱动,使用标准Linux的SDIO设备驱动。内核模块初始化入口module_init()调用dhd_wifi_platform_load_sdio()函数进行初始化工作,这里调用wifi_platform_set_power()进行GPIO上电,调用dhd_wlan_set_carddetect()进行探测SDIO设备卡,最后调用sdio_register_driver(&bcmsdh_sdmmc_driver);进行SDIO设备驱动的注册,SDIO总线已经检测到WiFi模块设备 根据设备号和厂商号与该设备驱动匹配, 所以立即回调该驱动的bcmsdh_sdmmc_probe()函数,这里进行WiFi模组芯片的初始化工作,最后创建net_device网络接口wlan0,然后注册到Linux内核协议栈中。 @@ -2557,7 +2558,7 @@ HDF WLAN驱动框架由Module、NetDevice、NetBuf、BUS、HAL、Client 和 Mess 代码流程框图如下: -dayu200-wifi-03.png +![dayu200-wifi-03.png](figures/dayu200/dayu200-wifi-03.png) 代码位于device/hihope/rk3568/wifi/bcmdhd_wifi6/hdf_driver_bdh_register.c @@ -2801,7 +2802,7 @@ p2p-p2p0-0 Link encap:Ethernet HWaddr 12:2c:6b:11:21:e0 Driver bcmsdh_sdmmc 蓝牙整体硬件架构上分为主机(计算机或MCU)和主机控制器(实际蓝牙芯片组)两部分;主机和控制器之间的通信遵循主机控制器接口(HCI),如下所示: - +![dayu200-bt-01.png](figures/dayu200/dayu200-bt-01.png) HCI定义了如何交换命令,事件,异步和同步数据包。异步数据包(ACL)用于数据传输,而同步数据包(SCO)用于带有耳机和免提配置文件的语音。 @@ -3148,7 +3149,7 @@ void hw_process_event(HC_BT_HDR *p_buf) 基于HDF(Hardware Driver Foundation)驱动框架开发的Sensor驱动模型 - +![dayu200-sensor-01.png](figures/dayu200/dayu200-sensor-01.png) rk3568 支持accel sensor,整体的驱动框架openharmony 主线已经具备,只需要实现具体的器件驱动即可。 @@ -3383,7 +3384,7 @@ Vibrator驱动模型主要包含Vibrator(传感器)相关的HDI接口与实 **图 1** Vibrator驱动模型图 - +![dayu200-vibrator-01.png](figures/dayu200/dayu200-vibrator-01.png) rk3568 支持线性马达,整体的驱动框架openharmony 主线已经具备,只需要实现具体的器件驱动即可。 diff --git a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md index 29de44f87158ba6f2d54bbe62de2a98413161f38..2c737a460b35f81ad954e496a21467a42c8f53da 100644 --- a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md +++ b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md @@ -715,7 +715,7 @@ board_ld_flags :链接选项,与Makefile中的LDFLAGS变量对应。 ### 内核基础功能适配 -内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)**、**[任务管理](../kernel/kernel-mini-basic-task.md)**、**[内存管理](../kernel/kernel-mini-basic-memory.md)**、**[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)**、**[时间管理](../kernel/kernel-basic-mini-time.md)**、**[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。 +内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)**、**[任务管理](../kernel/kernel-mini-basic-task.md)**、**[内存管理](../kernel/kernel-mini-basic-memory.md)**、**[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)**、**[时间管理](../kernel/kernel-mini-basic-time.md)**、**[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。 从上一节中打印信息输出时间间隔可以看出,`LOS_TaskDelay`函数的延时时间不准确,我们可以在`target_config.h`中定义如下宏进行内核时钟适配: diff --git a/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md b/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md index aaf0a675de0ddd55139c87b5375c55be025e17b9..ee236e2a7d0303f436e419a23536a5d54faf5c92 100644 --- a/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md +++ b/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md @@ -1551,7 +1551,8 @@ struct v4l2_buffer { - InputController:提供input设备的业务控制接口,包括获取器件信息及设备类型、设置电源状态等。 **图 1** INPUT模块HDI接口层框架图 -dayu200-tp-01.png + +![dayu200-tp-01.png](figures/dayu200/dayu200-tp-01.png) 相关目录下源代码目录结构如下所示 diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio.md b/zh-cn/device-dev/reference/hdi-apis/_audio.md index 4b9d2b89865f9c4dc73a96232a636a36a4d190de..722ca8820dcac1d8a751e0c3ef62b966607e7f5e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio.md @@ -85,7 +85,7 @@ Audio模块接口定义。 | [AudioSampleFormat](#audiosampleformat){ AUDIO_SAMPLE_FORMAT_S8, AUDIO_SAMPLE_FORMAT_S8P, AUDIO_SAMPLE_FORMAT_U8, AUDIO_SAMPLE_FORMAT_U8P,   AUDIO_SAMPLE_FORMAT_S16, AUDIO_SAMPLE_FORMAT_S16P, AUDIO_SAMPLE_FORMAT_U16, AUDIO_SAMPLE_FORMAT_U16P,   AUDIO_SAMPLE_FORMAT_S24, AUDIO_SAMPLE_FORMAT_S24P, AUDIO_SAMPLE_FORMAT_U24, AUDIO_SAMPLE_FORMAT_U24P,   AUDIO_SAMPLE_FORMAT_S32, AUDIO_SAMPLE_FORMAT_S32P, AUDIO_SAMPLE_FORMAT_U32, AUDIO_SAMPLE_FORMAT_U32P,   AUDIO_SAMPLE_FORMAT_S64, AUDIO_SAMPLE_FORMAT_S64P, AUDIO_SAMPLE_FORMAT_U64, AUDIO_SAMPLE_FORMAT_U64P,   AUDIO_SAMPLE_FORMAT_F32, AUDIO_SAMPLE_FORMAT_F32P, AUDIO_SAMPLE_FORMAT_F64, AUDIO_SAMPLE_FORMAT_F64P } | 原始音频样本格式 | | [AudioChannelMode](#audiochannelmode){  AUDIO_CHANNEL_NORMAL = 0, AUDIO_CHANNEL_BOTH_LEFT, AUDIO_CHANNEL_BOTH_RIGHT, AUDIO_CHANNEL_EXCHANGE,   AUDIO_CHANNEL_MIX, AUDIO_CHANNEL_LEFT_MUTE, AUDIO_CHANNEL_RIGHT_MUTE, AUDIO_CHANNEL_BOTH_MUTE } | 音频播放的通道模式 | | [AudioDrainNotifyType](#audiodrainnotifytype){ AUDIO_DRAIN_NORMAL_MODE, AUDIO_DRAIN_EARLY_MODE } | DrainBuffer函数结束类型 | -| [AudioCallbackType](#audiocallbacktype){ AUDIO_NONBLOCK_WRITE_COMPELETED, AUDIO_DRAIN_COMPELETED, AUDIO_FLUSH_COMPLETED, AUDIO_RENDER_FULL,   AUDIO_ERROR_OCCUR } | 回调函数通知事件类型 | +| [AudioCallbackType](#audiocallbacktype){ AUDIO_NONBLOCK_WRITE_COMPLETED, AUDIO_DRAIN_COMPLETED, AUDIO_FLUSH_COMPLETED, AUDIO_RENDER_FULL,   AUDIO_ERROR_OCCUR } | 回调函数通知事件类型 | | [AudioPortRole](#audioportrole){ AUDIO_PORT_UNASSIGNED_ROLE = 0, AUDIO_PORT_SOURCE_ROLE = 1, AUDIO_PORT_SINK_ROLE = 2 } | 音频端口角色 | | [AudioPortType](#audioporttype){ AUDIO_PORT_UNASSIGNED_TYPE = 0, AUDIO_PORT_DEVICE_TYPE = 1, AUDIO_PORT_MIX_TYPE = 2, AUDIO_PORT_SESSION_TYPE = 3 } | 音频端口类型. | | [AudioSessionType](#audiosessiontype){ AUDIO_OUTPUT_STAGE_SESSION = 0, AUDIO_OUTPUT_MIX_SESSION, AUDIO_ALLOCATE_SESSION, AUDIO_INVALID_SESSION } | 端口会话类型 | @@ -215,8 +215,8 @@ enum AudioCallbackType | 枚举值 | 描述 | | -------- | -------- | -| AUDIO_NONBLOCK_WRITE_COMPELETED | 非阻塞式写完成 | -| AUDIO_DRAIN_COMPELETED | DrainBuffer完成 | +| AUDIO_NONBLOCK_WRITE_COMPLETED | 非阻塞式写完成 | +| AUDIO_DRAIN_COMPLETED | DrainBuffer完成 | | AUDIO_FLUSH_COMPLETED | Flush完成 | | AUDIO_RENDER_FULL | Render缓冲区已满 | | AUDIO_ERROR_OCCUR | 发生了错误 | diff --git a/zh-cn/device-dev/reference/hdi-apis/audio__types_8h.md b/zh-cn/device-dev/reference/hdi-apis/audio__types_8h.md index 2f334779b02ffa64ba585e3713edad9b9ccf0371..48baaa842760e3dbae132136694f78d1359052ef 100644 --- a/zh-cn/device-dev/reference/hdi-apis/audio__types_8h.md +++ b/zh-cn/device-dev/reference/hdi-apis/audio__types_8h.md @@ -64,7 +64,7 @@ Audio模块接口定义中使用的自定义数据类型,包括音频端口、 | [AudioSampleFormat](_audio.md#audiosampleformat){ AUDIO_SAMPLE_FORMAT_S8, AUDIO_SAMPLE_FORMAT_S8P, AUDIO_SAMPLE_FORMAT_U8, AUDIO_SAMPLE_FORMAT_U8P,   AUDIO_SAMPLE_FORMAT_S16, AUDIO_SAMPLE_FORMAT_S16P, AUDIO_SAMPLE_FORMAT_U16, AUDIO_SAMPLE_FORMAT_U16P,   AUDIO_SAMPLE_FORMAT_S24, AUDIO_SAMPLE_FORMAT_S24P, AUDIO_SAMPLE_FORMAT_U24, AUDIO_SAMPLE_FORMAT_U24P,   AUDIO_SAMPLE_FORMAT_S32, AUDIO_SAMPLE_FORMAT_S32P, AUDIO_SAMPLE_FORMAT_U32, AUDIO_SAMPLE_FORMAT_U32P,   AUDIO_SAMPLE_FORMAT_S64, AUDIO_SAMPLE_FORMAT_S64P, AUDIO_SAMPLE_FORMAT_U64, AUDIO_SAMPLE_FORMAT_U64P,   AUDIO_SAMPLE_FORMAT_F32, AUDIO_SAMPLE_FORMAT_F32P, AUDIO_SAMPLE_FORMAT_F64, AUDIO_SAMPLE_FORMAT_F64P } | 原始音频样本格式 | | [AudioChannelMode](_audio.md#audiochannelmode){  AUDIO_CHANNEL_NORMAL = 0, AUDIO_CHANNEL_BOTH_LEFT, AUDIO_CHANNEL_BOTH_RIGHT, AUDIO_CHANNEL_EXCHANGE,   AUDIO_CHANNEL_MIX, AUDIO_CHANNEL_LEFT_MUTE, AUDIO_CHANNEL_RIGHT_MUTE, AUDIO_CHANNEL_BOTH_MUTE } | 音频播放的通道模式 | | [AudioDrainNotifyType](_audio.md#audiodrainnotifytype){ AUDIO_DRAIN_NORMAL_MODE, AUDIO_DRAIN_EARLY_MODE } | DrainBuffer函数结束类型 | -| [AudioCallbackType](_audio.md#audiocallbacktype){ AUDIO_NONBLOCK_WRITE_COMPELETED, AUDIO_DRAIN_COMPELETED, AUDIO_FLUSH_COMPLETED, AUDIO_RENDER_FULL,   AUDIO_ERROR_OCCUR } | 回调函数通知事件类型 | +| [AudioCallbackType](_audio.md#audiocallbacktype){ AUDIO_NONBLOCK_WRITE_COMPLETED, AUDIO_DRAIN_COMPLETED, AUDIO_FLUSH_COMPLETED, AUDIO_RENDER_FULL,   AUDIO_ERROR_OCCUR } | 回调函数通知事件类型 | | [AudioPortRole](_audio.md#audioportrole){ AUDIO_PORT_UNASSIGNED_ROLE = 0, AUDIO_PORT_SOURCE_ROLE = 1, AUDIO_PORT_SINK_ROLE = 2 } | 音频端口角色 | | [AudioPortType](_audio.md#audioporttype){ AUDIO_PORT_UNASSIGNED_TYPE = 0, AUDIO_PORT_DEVICE_TYPE = 1, AUDIO_PORT_MIX_TYPE = 2, AUDIO_PORT_SESSION_TYPE = 3 } | 音频端口类型. | | [AudioSessionType](_audio.md#audiosessiontype){ AUDIO_OUTPUT_STAGE_SESSION = 0, AUDIO_OUTPUT_MIX_SESSION, AUDIO_ALLOCATE_SESSION, AUDIO_INVALID_SESSION } | 端口会话类型 | diff --git a/zh-cn/device-dev/security/security-guidelines-overall.md b/zh-cn/device-dev/security/security-guidelines-overall.md index 948fccd9efb8611098db00444917a9f30a8a1af5..465d5b3117c96acf458c488d491787b30bd64767 100644 --- a/zh-cn/device-dev/security/security-guidelines-overall.md +++ b/zh-cn/device-dev/security/security-guidelines-overall.md @@ -9,6 +9,7 @@ OpenHarmony操作系统是一个开放的系统,开发者可以通过OpenHarmo **图1** 安全保障示意图 + ![zh-cn_image_0000001058270836](figures/zh-cn_image_0000001058270836.png) @@ -73,7 +74,7 @@ OpenHarmony操作系统是一个开放的系统,开发者可以通过OpenHarmo 下图描述了DAC在文件访问时的鉴权过程,首先匹配进程uid和文件uid属性,其次匹配进程gid和文件gid属性,最后都匹配失败的情况,判断文件other属性是否支持进程的读、写、执行操作。同时支持忽略DAC检测机制(读、写、执行)作为一组系统特权(Capability),支持高权限(如系统服务)对低权限(三方APP)的文件管理。 **图2** DAC流程图 - + ![zh-cn_image_0000001057233092](figures/zh-cn_image_0000001057233092.png) - **Capability机制** @@ -102,6 +103,7 @@ OpenHarmony操作系统是一个开放的系统,开发者可以通过OpenHarmo HUKS(OpenHarmony Universal Keystore Service),提供了密钥管理、证书管理服务,当前在OpenHarmony上主要提供密钥管理服务,用于支撑HiChain(设备身份认证平台)的基础设备认证。如下是HUKS的功能结构图: **图3** HUKS功能结构图 + ![zh-cn_image_0000001159520844](figures/zh-cn_image_0000001159520844.png) 支持算法包括: @@ -144,6 +146,7 @@ HUKS本身不考虑多个应用同时调用的情况,因为HUKS只是一个lib **图4** 设备间建立可信关系流程图 + ![zh-cn_image_0000001058382954](figures/zh-cn_image_0000001058382954.png) diff --git a/zh-cn/device-dev/security/security.md b/zh-cn/device-dev/security/security.md deleted file mode 100644 index 1d9db4c8610e88ab991a455bc8be6fc56db2e36c..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/security/security.md +++ /dev/null @@ -1,7 +0,0 @@ -# 隐私与安全 - -- **[隐私保护](security-privacy-protection.md)** - -- **[安全指南](security-guidelines-overall.md)** - - diff --git a/zh-cn/device-dev/subsystems/subsys-ota-guide.md b/zh-cn/device-dev/subsystems/subsys-ota-guide.md index 9e42bfedb9f76f9baf59cb349921c0db0dbf3810..ee50d17f78ece666528dbc6d0d194cdbd6944421 100644 --- a/zh-cn/device-dev/subsystems/subsys-ota-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-ota-guide.md @@ -27,28 +27,25 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 ### 约束与限制 -- 支持基于Hi3861/Hi3518EV300/Hi3516DV300芯片的开源套件。 +- 支持基于Hi3861/Hi3516DV300/RK3568芯片的开源套件。 -- 对Hi3518EV300/Hi3516DV300开源套件,设备需要支持SD卡(VFAT格式)。 +- 对Hi3516DV300/RK3568开源套件,设备需要支持SD卡(VFAT格式)。 - 生成升级包需要在linux系统下面执行。 - 目前轻量和小型系统仅支持全量包升级,暂不支持差分包、变分区包升级。 +- AB 升级只适用于标准系统支持 AB 分区启动的设备。 + ## 环境准备 - 在Windows上,下载安装OpenSSL工具,并配置环境变量。 - 准备升级包制作工具 - 编译出版本镜像文件 -- 制作升级包需要 Linux 系统环境 -- AB 升级只适用于标准系统支持 AB 分区启动的设备 - - -## OTA 升级指导 -### 开发流程 +## 开发流程 1. 使用OpenSSL工具生成公私钥对 @@ -71,31 +68,33 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包   5.2 AB 升级场景 -### 开发步骤 +## 开发步骤 -#### 生成公私钥对 +### 生成公私钥对 1. 使用OpenSSL工具生成公私钥对。 -3. 请妥善保管私钥文件,在升级包制作过程中将私钥文件作为制作命令的参数带入,用于升级包签名,公钥用于升级时对升级包进行签名校验,公钥的放置如下: 轻量和小型系统将生成的公钥内容预置在代码中,需要厂商实现 HotaHalGetPubKey 这个接口来获取公钥。标准系统需要将生成的公钥放在 ./device/hisilicon/hi3516dv300/build/updater_config/signing_cert.crt 这个文件中。 +3. 请妥善保管私钥文件,在升级包制作过程中将私钥文件作为制作命令的参数带入,用于升级包签名,公钥用于升级时对升级包进行签名校验,公钥的放置如下: 轻量和小型系统将生成的公钥内容预置在代码中,需要厂商实现 HotaHalGetPubKey 这个接口来获取公钥。标准系统需要将生成的公钥放在device或vendor目录下的 /hisilicon/hi3516dv300/build/updater_config/signing_cert.crt 这个文件中。 -5. 对使用 Hi3518EV300/Hi3516DV300 套件的轻量和小型系统,在上一步的基础上,还需用public_arr.txt里面的全部内容替换uboot模块device\hisilicon\third_party\uboot\u-boot-2020.01\product\hiupdate\verify\update_public_key.c 中的g_pub_key中的全部内容。 +5. 对使用 Hi3516DV300 套件的小型系统,在上一步的基础上,还需用public_arr.txt里面的全部内容替换uboot模块third_party\u-boot\u-boot-2020.01\product\hiupdate\verify\update_public_key.c 中的g_pub_key中的全部内容。 示例,uboot模块的公钥: ```c - static unsigned char g_pub_key[PUBKEY_LEN] = { + static unsigned char g_pub_key[] = { 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, 0x00, 0xBF, 0xAA, 0xA5, 0xB3, 0xC2, 0x78, 0x5E, } ``` -#### 制作升级包 +### 制作升级包 -##### 轻量与小型系统升级包制作 +#### 轻量与小型系统升级包制作 1. 创建目标版本(target_package)文件夹,文件格式如下: + + 轻量级系统和AB升级的小型系统不需要 OTA.tag 和 config。 ```text target_package @@ -136,9 +135,9 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 | 头信息(head节点) | info节点 | / | 必填 | 该节点内容配置为:head info | | 头信息(head节点) | info节点 | fileVersion | 必填 | 保留字段,内容不影响升级包生成 | | 头信息(head节点) | info节点 | prdID | 必填 | 保留字段,内容不影响升级包生成 | - | 头信息(head节点) | info节点 | softVersion | 必填 | 软件版本号,即升级包版本号,版本必须在“VERSION.mbn”范围内,否则无法生产升级 | + | 头信息(head节点) | info节点 | softVersion | 必填 | 软件版本号,即升级包版本号,版本必须比基础版本大,且OpenHarmony后没有其他字母,否则无法生产升级 | | 头信息(head节点) | info节点 | _date_ | _必填_ | 升级包制作日期,保留字段,不影响升级包生成 | - | 头信息(head节点) | info节点 | _time_ | _必填_ | 升级包制作时间,保留字段,不影响升级包生成 | + | 头信息(head节点) | info节点 | _time_ | _必填_ | 升级包制作时间,保留字段,不影响升级包生成 | | 组件信息(group节点) | component节点 | / | 必填 | 该节点内容配置为:要打入升级包的组件/镜像文件的路径,默认为版本包根路径 | | 组件信息(group节点) | component节点 | compAddr | 必填 | 该组件所对应的分区名称,例如:system、vendor等。 | | 组件信息(group节点) | component节点 | compId | 必填 | 组件Id,不同组件Id不重复 | @@ -178,8 +177,7 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 - -nl2:打开非“标准系统”模式开关 -##### 标准系统升级包制作 - +#### 标准系统升级包制作 1. 创建目标版本(target_package)文件夹,文件格式如下: @@ -195,7 +193,11 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 └── updater_specified_config.xml ``` -2. 将待升级的组件,包括镜像文件(例如:system.img)等放入目标版本文件夹的根目录下,代替上文结构中的{component_N}部分。 +2. 将待升级的组件(包括镜像文件和updater_binary文件)放入目标版本文件夹的根目录下,代替上文结构中的{component_N}部分。 + + 以RK3568为例,镜像文件的构建位置为:out/rk3568/packages/phone/images/ + + 二进制升级文件updater_binary位置为:out/rk3568/packages/phone/system/bin/ 3. 填写“updater_config”文件夹中的组件配置文件。 @@ -206,9 +208,11 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 ```text HI3516 - HI3518 + RK3568 ``` + 厂家可在路径base/updater/updater/utils/utils.cpp文件中的GetLocalBoardId()接口进行Local BoardId的配置。请确保utils.cpp文件中的Local BoardId包含在BOARD.list中,否则无法升级。 + 5. 配置“updater_config”文件夹中当前升级包所支持的版本范围:**VERSION.mbn**。 版本名称格式:Hi3516DV300-eng 10 QP1A.XXXXXX.{大版本号(6位)}.XXX{小版本号(3位)}。 @@ -221,9 +225,10 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 ```text Hi3516DV300-eng 10 QP1A.190711.001 Hi3516DV300-eng 10 QP1A.190711.020 - Hi3518DV300-eng 10 QP1A.190711.021 ``` + 请确保基础版本号包含在VERSION.mbn中 + 6. 针对增量(差分)升级包,还需要准备一个源版本(source_package),文件内容格式与目标版本(target_package)相同,需要打包成zip格式,即为:source_package.zip。 7. 针对变分区升级包,还需要提供分区表文件“partition_file.xml”,partition_file.xml配置节点说明如下,可通过-pf参数指定。 @@ -264,7 +269,7 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 - ./target_package/:指定target_package路径。 - ./output_package/:指定升级包输出路径。 - - -pk ./rsa_private_key3072.pem:指定私钥文件路径。 + - -pk ./rsa_private_key2048.pem:指定私钥文件路径。 **增量(差分)升级包** @@ -278,7 +283,7 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 - ./target_package/:指定target_package路径。 - ./output_package/:指定升级包输出路径。 - -s ./source_package.zip:指定“source_package.zip”路径,当存在镜像需要进行差分处理时,必须使用-s参数指定source版本包。 - - -pk ./rsa_private_key3072.pem:指定私钥文件路径。 + - -pk ./rsa_private_key2048.pem:指定私钥文件路径。 **变分区升级包** @@ -291,23 +296,23 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 - ./target_package/:指定target_package路径。 - ./output_package/:指定升级包路径。 - - -pk ./rsa_private_key3072.pem:指定私钥文件路径。 + - -pk ./rsa_private_key2048.pem:指定私钥文件路径。 - -pf ./partition_file.xml:指定分区表文件路径。 -#### 上传升级包 +### 上传升级包 将升级包上传到厂商的OTA服务器。 -#### 下载升级包 +### 下载升级包 1. 厂商应用从OTA服务器下载升级包。 -2. 对Hi3518EV300/Hi3516DV300开源套件,需要插入SD卡(容量>100MBytes)。 +2. 对Hi3516DV300开源套件,需要插入SD卡(容量>100MBytes)。 -#### 厂商应用集成OTA能力 +### 厂商应用集成OTA能力 1. 轻量与小型系统 @@ -319,12 +324,12 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 2. 标准系统请参考[JS参考规范](../../application-dev/reference/apis/js-apis-update.md)指导中的升级接口参考规范。 -##### API 应用默认场景 +#### API 应用默认场景 升级包是按照上文“生成公私钥对”和“生成升级包”章节制作的。 -###### 开发指导 +##### 开发指导 1. 应用侧通过下载,获取当前设备升级包后,调用HotaInit接口初始化OTA模块。 @@ -333,7 +338,7 @@ OTA 的升级原理是利用升级包制作工具,将编译出的版本打包 3. 写入完成后,调用HotaRestart接口重启系统,升级过程中,使用HotaCancel接口可以取消升级。 -###### 示例代码 +##### 示例代码 使用OpenHarmony的“升级包格式和校验方法”进行升级。 @@ -388,12 +393,12 @@ int main(int argc, char **argv) ``` -##### API 应用定制场景 +#### API 应用定制场景 升级包不是按照上文“生成公私钥对”和“生成升级包”章节制作的,是通过其它方式制作的。 -###### 开发指导 +##### 开发指导 1. 应用侧通过下载,获取当前设备升级包后,调用HotaInit接口初始化。 @@ -408,7 +413,7 @@ int main(int argc, char **argv) 6. 调用HotaRestart接口,进行重启,升级过程中,使用HotaCancel接口可以取消升级。 -###### 示例代码 +##### 示例代码 使用非OpenHarmony的“升级包格式和校验方法“进行升级。 @@ -480,11 +485,11 @@ int main(int argc, char **argv) ``` -###### 系统升级 +##### 系统升级 厂商应用调用OTA模块的API,OTA模块执行升级包的签名验证、版本防回滚、烧写落盘功能,升级完成后自动重启系统。 -对于使用Hi3518EV300/Hi3516DV300开源套件的轻量和小型系统,在需要实现防回滚功能的版本中,需要增加LOCAL_VERSION的值,如"ohos default 1.0"->"ohos default 1.1",LOCAL_VERSION在device\hisilicon\third_party\uboot\u-boot-2020.01\product\hiupdate\ota_update\ota_local_info.c中。 +对于使用Hi3516DV300开源套件的轻量和小型系统,在需要实现防回滚功能的版本中,需要增加LOCAL_VERSION的值,如"ohos default 1.0"->"ohos default 1.1",LOCAL_VERSION在device\hisilicon\third_party\uboot\u-boot-2020.01\product\hiupdate\ota_update\ota_local_info.c中。 示例,增加版本号。 @@ -492,16 +497,15 @@ int main(int argc, char **argv) const char *get_local_version(void) { #if defined(CONFIG_TARGET_HI3516EV200) || \ - defined(CONFIG_TARGET_HI3516DV300) || \ - defined(CONFIG_TARGET_HI3518EV300) + defined(CONFIG_TARGET_HI3516DV300) #define LOCAL_VERSION "ohos default 1.0" /* increase: default release version */ ``` -##### AB 升级场景 +#### AB 升级场景 -###### 开发流程 +##### 开发流程 1. 应用侧下载获取当前设备升级包 2. update_service 通过 SAMGR 将系统安装部件拉起 @@ -509,7 +513,7 @@ const char *get_local_version(void) 4. 下一次重启时激活新版本 -###### 开发步骤 +##### 开发步骤 - JS API 通过 update_service 模块处理AB升级相关流程 @@ -528,7 +532,7 @@ const char *get_local_version(void) 1.拉起系统安装服务,并建立IPC连接: ```cpp - int SysInstallerInit(void * callback) + int SysInstallerInit(void* callback) ``` 2.安装指定路径的AB升级包: @@ -538,7 +542,7 @@ const char *get_local_version(void) 3.设置进度回调: ```cpp - int SetUpdateProgressCallback(void * callback) + int SetUpdateProgressCallback(void* callback) ``` 4.获取升级包安装状态(0 未开始,1 安装中,2 安装结束): @@ -570,7 +574,7 @@ const char *get_local_version(void) ``` -###### 常见问题 +##### 常见问题 1. 升级包下载,安装过程出现异常
系统保持当前版本继续运行,在下一个搜包周期重新完成版本升级过程 @@ -579,6 +583,6 @@ const char *get_local_version(void)
需要进行异常回滚,并将无法启动的分区设置为 unbootable,下次则不从该分区启动 -###### 调测验证 +##### 调测验证 设备能在正常使用的情况下,在后台从服务器下载升级包,完成静默升级,并按照厂商设置的策略重启激活版本。 \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-tel.md b/zh-cn/device-dev/subsystems/subsys-tel.md deleted file mode 100644 index 18fb1c222599057d529dbf0547723e8cc8b270e6..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-tel.md +++ /dev/null @@ -1,7 +0,0 @@ -# 电话服务 - - - -- **[电话服务概述](subsys-tel-overview.md)** - -- **[电话服务开发指导](subsys-tel-guide.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md b/zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md index f5fbe44ae9d0121ac77eec21f7d8e66b4e2756ad..d7cc6d5feb9e3306f25d692bfb764e87248b2922 100644 --- a/zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @@ -1,30 +1,30 @@ -# hdc_std使用指导 +# hdc使用指导 -hdc_std(OpenHarmony Device Connector)是 OpenHarmony 为开发人员提供的用于调试的命令行工具,通过该工具可以在Windows/Linux/MacOS等系统上与开发机或者模拟器进行交互。 +hdc(OpenHarmony Device Connector)是 OpenHarmony 为开发人员提供的用于调试的命令行工具,通过该工具可以在Windows/Linux/MacOS等系统上与开发机或者模拟器进行交互。 -下文将介绍hdc_std的环境准备和常用命令及使用举例。 +下文将介绍hdc的环境准备和常用命令及使用举例。 ## 环境准备 -**hdc_std 工具获取方式:** +**hdc 工具获取方式:** -通过OpenHarmony sdk获取,hdc_std在sdk的toolchains目录下。 +通过OpenHarmony sdk获取,hdc在sdk的toolchains目录下。 **使用举例:** 下面以windows侧使用方式举例: -获取windows的sdk,将hdc_std.exe放到磁盘某个位置即可使用。 +获取windows的sdk,将hdc.exe放到磁盘某个位置即可使用。 ## 注意事项 -- 使用hdc_std,如果出现异常,可以尝试通过hdc_std kill命令杀掉hdc_std服务,或者通过hdc_std start -r命令重启服务进程进行解决。 +- 使用hdc,如果出现异常,可以尝试通过hdc kill命令杀掉hdc服务,或者通过hdc start -r命令重启服务进程进行解决。 -- 如果出现hdc_std list targets获取不到设备信息,通过任务管理器查看是否有hdc_std进程存在,如果进程存在,可以通过杀掉该进程进行解决。 +- 如果出现hdc list targets获取不到设备信息,通过任务管理器查看是否有hdc进程存在,如果进程存在,可以通过杀掉该进程进行解决。 ## option相关的命令 @@ -36,29 +36,29 @@ option涉及以下命令: 用于显示hdc相关的帮助、版本信息。 **表1** 命令说明 - - | 返回值 | 返回值说明| + + | 返回值 | 返回值说明| | -------- | -------- | - | 返回对应信息 | 帮助或者版本信息 | + | 返回对应信息 | 帮助或者版本信息 | 使用方法: - + ``` - hdc_std -h / hdc_std help + hdc -h / hdc help ``` - + ``` - hdc_std -v / hdc_std version + hdc -v / hdc version ``` - **-l 0-5** 用于指定运行时日志等级,默认为LOG_INFO。 **表2** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | | 0 | LOG_OFF | | 1 | LOG_FATAL| @@ -70,27 +70,27 @@ option涉及以下命令: 使用方法: ``` - hdc_std -l5 start + hdc -l5 start ``` - **-t key** 用于连接指定设备标识为key的设备。 **表3** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | key | 为 IP地址:port 格式,或者USB序列号 | - | **返回值** | **返回值说明** | - | ①error: device '\*\*\*' not found
②Nothing to do... | ①设备不存在
②附加的命令不存在 | + | key | 为 IP地址:port 格式,或者USB序列号 | + | **返回值** | **返回值说明** | + | ①error: device '\*\*\*' not found
②Nothing to do... | ①设备不存在
②附加的命令不存在 | 使用方法: 该option需要与具体的操作命令搭配使用,下面以shell命令举例: - hdc_std list targets (获取设备信息) + hdc list targets (获取设备信息) - hdc_std -t _key_ shell (-t后面添加的_key_ 需要替换为上面查询的设备信息) + hdc -t _key_ shell (-t后面添加的_key_ 需要替换为上面查询的设备信息) > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 一台开发机可支持多个设备连接,每个设备有其唯一的设备标识,如果通过网络与设备连接,其标识为IP地址:port格式,如果通过USB连接则标识为设备sn号。该命令需要跟随具体操作命令。 @@ -99,15 +99,15 @@ option涉及以下命令: 用于获取client-server版本。 **表4** 命令说明 - - | 返回值 | 返回值说明| + + | 返回值 | 返回值说明| | -------- | -------- | | Client version: server version: | client-server版本号 | 使用方法: ``` - hdc_std checkserver + hdc checkserver ``` @@ -115,7 +115,7 @@ option涉及以下命令: 查询设备列表涉及以下命令: - + ``` list targets[-v] ``` @@ -126,25 +126,25 @@ list targets[-v] **表5** 命令说明 -| 参数 | 参数说明| +| 参数 | 参数说明| | -------- | -------- | -| -v | 添加-v选项,则会打印设备详细信息 | -| **返回值** | **返回值说明** | -| ①返回设备信息
②[Empty] | ①已经连接的设备列表信息
②没有查询到设备信息 | +| -v | 添加-v选项,则会打印设备详细信息 | +| **返回值** | **返回值说明** | +| ①返回设备信息
②[Empty] | ①已经连接的设备列表信息
②没有查询到设备信息 | 使用方法: - + ``` -hdc_std list targets +hdc list targets ``` - + ``` -hdc_std list targets -v +hdc list targets -v ``` @@ -157,18 +157,18 @@ hdc_std list targets -v 以读写模式挂载系统分区。 **表6** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | 无 | 无 | - | **返回值** | **返回值说明** | - | ①Mount finish
②返回具体信息 | ①成功情况下返回的信息
②失败情况下的具体信息 | + | 无 | 无 | + | **返回值** | **返回值说明** | + | ①Mount finish
②返回具体信息 | ①成功情况下返回的信息
②失败情况下的具体信息 | 使用方法: - + ``` - hdc_std target mount + hdc target mount ``` - **target boot** @@ -176,9 +176,9 @@ hdc_std list targets -v 使用方法: - + ``` - hdc_std target boot + hdc target boot ``` - **smode [-r]** @@ -186,48 +186,48 @@ hdc_std list targets -v 使用方法: - + ``` - hdc_std smode + hdc smode ``` - + ``` - hdc_std smode -r + hdc smode -r ``` - **kill [-r]** 终止服务进程。 **表7** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | -r | 触发服务重启 | - | **返回值** | **返回值说明** | - | ①Kill server finish
②返回具体信息 | ①成功情况下返回的信息
②失败情况下的具体信息 | + | -r | 触发服务重启 | + | **返回值** | **返回值说明** | + | ①Kill server finish
②返回具体信息 | ①成功情况下返回的信息
②失败情况下的具体信息 | 使用方法: - + ``` - hdc_std kill + hdc kill ``` - **start [-r]** 启动服务进程。 **表8** 命令说明 - + | 参数 | 参数说明 | | -------- | -------- | - | -r | 如果服务进程已经启动,-r选项会触发服务进程重新启动 | - | **返回值** | **返回值说明** | - | 无 | 无 | + | -r | 如果服务进程已经启动,-r选项会触发服务进程重新启动 | + | **返回值** | **返回值说明** | + | 无 | 无 | 使用方法: - + ``` - hdc_std start + hdc start ``` @@ -240,55 +240,55 @@ hdc_std list targets -v 通过【ip地址:端口号】来指定连接的设备 **表9** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | host[:port] | 为IP地址:port格式 | - | -remove | 表示断开与指定设备的连接 | - | **返回值** | **返回值说明** | - | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | + | host[:port] | 为IP地址:port格式 | + | -remove | 表示断开与指定设备的连接 | + | **返回值** | **返回值说明** | + | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | 使用方法(举例): - + ``` - hdc_std tconn 192.168.0.100:8710 + hdc tconn 192.168.0.100:8710 ``` - **tmode usb** 执行后设备端对应daemon进程重启,并首先选用USB连接方式。 **表10** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | 无 | 无 | - | **返回值** | **返回值说明** | - | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | + | 无 | 无 | + | **返回值** | **返回值说明** | + | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | 使用方法: - + ``` - hdc_std tmode usb + hdc tmode usb ``` - **tmode port port-number** 执行后设备端对应daemon进程重启,并优先使用网络方式连接设备,如果连接设备失败,再选择USB连接。 **表11** 命令说明 - + | 参数 | 参数说明 | - | -------- | -------- | - | port-number | listen连接的网络端口号 | - | **返回值** | **返回值说明** | - | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | + | -------- | -------- | + | port-number | listen连接的网络端口号 | + | **返回值** | **返回值说明** | + | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | 使用方法: - + ``` - hdc_std tmode port 8710 + hdc tmode port 8710 ``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** @@ -299,9 +299,9 @@ hdc_std list targets -v 使用方法: - + ``` - hdc_std fport tcp:1234 tcp:1080 + hdc fport tcp:1234 tcp:1080 ``` - **rport remotenode localnode** @@ -309,28 +309,28 @@ hdc_std list targets -v 使用方法: - + ``` - hdc_std rport tcp:2080 tcp:2345 + hdc rport tcp:2080 tcp:2345 ``` - **fport ls** 列出全部转发端口转发任务。 **表12** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | 无 | 无 | - | **返回值** | **返回值说明** | - | 'tcp:1234 tcp:1080' [Forward] | 正向端口转发任务 | - | 'tcp:2080 tcp:2345' [Reverse] | 反向端口转发任务 | + | 无 | 无 | + | **返回值** | **返回值说明** | + | 'tcp:1234 tcp:1080' [Forward] | 正向端口转发任务 | + | 'tcp:2080 tcp:2345' [Reverse] | 反向端口转发任务 | 使用方法: - + ``` - hdc_std fport ls + hdc fport ls ``` - **fport rm** @@ -338,9 +338,9 @@ hdc_std list targets -v 使用方法: - + ``` - hdc_std fport rm tcp:1234 tcp:1080 + hdc fport rm tcp:1234 tcp:1080 ``` @@ -353,39 +353,39 @@ hdc_std list targets -v 发送文件至远端设备。 **表13** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | local | 本地待发送文件路径 | - | remote | 远程待接收文件路径 | - | **返回值** | **返回值说明** | - | ①返回具体信息
②返回传输结果 | ①失败情况下的具体信息
②成功传输的结果信息 | + | local | 本地待发送文件路径 | + | remote | 远程待接收文件路径 | + | **返回值** | **返回值说明** | + | ①返回具体信息
②返回传输结果 | ①失败情况下的具体信息
②成功传输的结果信息 | 使用方法(举例): - + ``` - hdc_std file send E:\a.txt /data/local/tmp/a.txt + hdc file send E:\a.txt /data/local/tmp/a.txt ``` - **file recv [-a] remote local** 从远端设备接收文件至本地。 **表14** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | -a | 文件保留时间戳模式 | - | local | 本地待接收文件路径 | - | remote | 远程待发送文件路径 | - | **返回值** | **返回值说明** | - | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | + | -a | 文件保留时间戳模式 | + | local | 本地待接收文件路径 | + | remote | 远程待发送文件路径 | + | **返回值** | **返回值说明** | + | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | 使用方法(举例): - + ``` - hdc_std file recv /data/local/tmp/a.txt ./a.txt + hdc file recv /data/local/tmp/a.txt ./a.txt ``` @@ -398,40 +398,40 @@ hdc_std list targets -v 安装OpenHarmony APP package。 **表15** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | package | OpenHarmony应用安装包文件名 | - | -r | 替换已存在应用 | - | -d | 允许降级安装 | - | -g | 应用动态授权 | - | **返回值** | **返回值说明** | - | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | + | package | OpenHarmony应用安装包文件名 | + | -r | 替换已存在应用 | + | -d | 允许降级安装 | + | -g | 应用动态授权 | + | **返回值** | **返回值说明** | + | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | 使用方法(举例): - + ``` - hdc_std install hwadmin.hap + hdc install hwadmin.hap ``` - **uninstall [-k] package** 卸载OpenHarmony应用。 **表16** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | package | OpenHarmony应用安装包 | - | -k | 保留/data/cache | - | **返回值** | **返回值说明** | - | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | + | package | OpenHarmony应用安装包 | + | -k | 保留/data/cache | + | **返回值** | **返回值说明** | + | ①返回具体信息
②无 | ①失败情况下的具体信息
②成功情况下无返回值 | 使用方法(举例): - + ``` - hdc_std uninstall package + hdc uninstall package ``` @@ -444,43 +444,43 @@ hdc_std list targets -v 支持抓取log信息。 **表17** 命令说明 - - | 参数 | 参数说明 | + + | 参数 | 参数说明 | | -------- | -------- | - | 无 | 无 | - | **返回值** | **返回值说明** | - | 返回具体信息 | 抓取的日志信息 | + | 无 | 无 | + | **返回值** | **返回值说明** | + | 返回具体信息 | 抓取的日志信息 | 抓取hilog日志: - + ``` - hdc_std hilog + hdc hilog ``` 清理hilog缓存日志: - + ``` - hdc_std shell "hilog -r" + hdc shell "hilog -r" ``` - **shell [_command_]** 远程执行命令或进入交互命令环境。 **表18** 命令说明 - + | 参数 | 参数说明 | - | -------- | -------- | - | command | 需要执行的单次命令 | - | **返回值** | **返回值说明** | - | 返回具体信息 | shell后面执行命令的结果信息 | + | -------- | -------- | + | command | 需要执行的单次命令 | + | **返回值** | **返回值说明** | + | 返回具体信息 | shell后面执行命令的结果信息 | 使用方法: - + ``` - hdc_std shell + hdc shell ``` - **jpid** @@ -488,36 +488,39 @@ hdc_std list targets -v 使用方法: - + ``` - hdc_std jpid + hdc jpid ``` ## 常见问题 -### hdc_std连接不到设备 +### hdc连接不到设备 - **现象描述** - 执行 "hdc_std list targets"命令后结果为:[Empty] + 执行 "hdc list targets"命令后结果为:[Empty] - **解决方法** 1. 设备没有被识别: 在设备管理器中查看是否有hdc设备,在通用串行总线设备中会有“HDC Device”信息。如果没有,hdc无法连接。此时需要断开并重联PC和OpenHarmony设备之间的USB连接,或者烧写最新的镜像。 - 2. hdc_std工作异常: + 2. hdc工作异常: 可以执行"hdc kill"或者"hdc start -r"杀掉hdc服务或者重启hdc服务,然后再执行hdc list targets查看是否已经可以获取设备信息。 - 3. hdc_std与设备不匹配: - 如果设备烧写的是最新镜像,hdc_std也需要使用最新版本。 + 3. hdc与设备不匹配: + 如果设备烧写的是最新镜像,hdc也需要使用最新版本。 -### hdc_std运行不了 +### hdc运行不了 - **现象描述** - 点击hdc_std.exe文件无法运行。 + 点击hdc.exe文件无法运行。 - **解决方法** - hdc_std.exe不需要安装,直接放到磁盘上就能使用,也可以添加到环境变量中。通过打开cmd执行hdc_std命令直接使用。 + 1. 运行环境异常: + linux版本建议ubuntu 18.04以上 64位,其他相近版本也可;libc++.so引用错误请使用ldd/readelf等命令检查库引用 windows版本建议windows10 64位,如果低版本windows winusb库缺失,请使用zadig更新库。对于复合设备,需要使用zadig工具安装libusb-win32驱动。 + 2. 如何运行hdc.exe: + hdc.exe不需要安装,直接放到磁盘上就能使用,也可以添加到环境变量中。通过打开cmd执行hdc命令直接使用。 ### hdc client如何远程访问hdc server @@ -529,13 +532,13 @@ hdc_std list targets -v - **连接步骤** 1. 关闭本地sever: ``` - hdc_std kill + hdc kill ``` 2. **-s [ip:]port -m** 启动远程server: ``` - hdc_std -s severIP:8710 -m + hdc -s severIP:8710 -m ``` 3. **-s [ip:]port command** 指定server执行指令: ``` - hdc_std -s severIP:8710 list targets + hdc -s severIP:8710 list targets ``` diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index f26f2863bbd04c491f1e4ab3b90d6057e057cf9f..0ece4c28eb5f077f564cae8a07c60d40b5fd68e7 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -166,8 +166,9 @@ - [互斥锁](kernel/kernel-mini-basic-ipc-mutex.md) - [消息队列](kernel/kernel-mini-basic-ipc-queue.md) - [信号量](kernel/kernel-mini-basic-ipc-sem.md) - - [时间管理](kernel/kernel-basic-mini-time.md) + - [时间管理](kernel/kernel-mini-basic-time.md) - [软件定时器](kernel/kernel-mini-basic-soft.md) + - [双向链表](kernel/kernel-mini-basic-list.md) - 扩展组件 - [C++支持](kernel/kernel-mini-extend-support.md) - [CPU占用率](kernel/kernel-mini-extend-cpup.md) @@ -180,7 +181,6 @@ - [LMS调测](kernel/kernel-mini-memory-lms.md) - 附录 - [内核编码规范](kernel/kernel-mini-appx-code.md) - - [双向链表](kernel/kernel-mini-appx-data-list.md) - [标准库支持](kernel/kernel-mini-appx-lib.md) - 小型系统内核(LiteOS-A) - [小型系统内核概述](kernel/kernel-small-overview.md) @@ -319,6 +319,7 @@ - HDF驱动框架 - [HDF开发概述](driver/driver-hdf-overview.md) - [驱动开发](driver/driver-hdf-development.md) + - [驱动加载](driver/driver-hdf-load.md) - [驱动服务管理](driver/driver-hdf-servicemanage.md) - [驱动消息机制管理](driver/driver-hdf-message-management.md) - [配置管理](driver/driver-hdf-manage.md) diff --git a/zh-cn/readme/figures/build_framework_ZN.PNG b/zh-cn/readme/figures/build_framework_ZN.PNG deleted file mode 100644 index 03f4d6f6cffc9d3552f86f197230d01a50e2860e..0000000000000000000000000000000000000000 Binary files a/zh-cn/readme/figures/build_framework_ZN.PNG and /dev/null differ diff --git "a/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" index 60c32bac0ca677738ef065c6031bfc432d2c69e1..2856eb0a36a3206d34b12b6a422aaa1a737f832b 100755 --- "a/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" @@ -1,10 +1,5 @@ # 启动恢复子系统 -- [简介](#section11660541593) -- [目录](#section161941989596) -- [约束](#section1718733212019) -- [使用说明](#section8533192617117) -- [相关仓](#section1371113476307) ## 简介 @@ -14,7 +9,7 @@ 支持使用LiteOS-A和Linux内核的平台。 - 负责处理从内核加载第一个用户态进程开始,到第一个应用程序启动之间的系统服务进程启动过程。启动恢复子系统除负责加载各系统关键进程之外,还需在启动的同时设置其对应权限,并在子进程启动后对指定进程实行保活(若进程意外退出要重新启动),对于核心进程意外退出时,启动恢复子系统还要执行系统重启操作。详见“[init启动引导组件](../device-dev/subsystems/subsys-boot-init.md)”部分。 + 负责处理从内核加载第一个用户态进程开始,到第一个应用程序启动之间的系统服务进程启动过程。启动恢复子系统除负责加载各系统关键进程之外,还需在启动的同时设置其对应权限,并在子进程启动后对指定进程实行保活(若进程意外退出要重新启动),对于核心进程意外退出时,启动恢复子系统还要执行系统重启操作。详见“[init启动引导组件](../device-dev/subsystems/subsys-boot-init-cfg.md)”部分。 - appspawn应用孵化器组件 @@ -33,7 +28,7 @@ 负责提供获取与设置操作系统相关的系统属性。 - 支持全量系统平台。支持的系统属性包括:默认系统属性、OEM厂商系统属性和自定义系统属性。OEM厂商部分仅提供默认值,具体值需OEM产品方按需进行调整,详见“[syspara系统属性组件](../device-dev/subsystems/subsys-boot-syspara.md)”部分。 + 支持全量系统平台。支持的系统属性包括:默认系统属性、OEM厂商系统属性和自定义系统属性。OEM厂商部分仅提供默认值,具体值需OEM产品方按需进行调整,详见“[syspara系统属性组件](../device-dev/subsystems/subsys-boot-init-sysparam.md)”部分。 ## 目录 diff --git "a/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" index 2a5c008647203981e2da766e24c29bb14173d476..123e8b3acb357954dac6cb1c00e7db9ad3a90df6 100644 --- "a/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" @@ -1,20 +1,12 @@ # 用户IAM子系统 -- [简介](#简介) -- [目录](#目录) -- [约束](#约束) -- [说明](#说明) - - [使用说明](#使用说明) -- [相关仓](#相关仓) - - ## 简介 用户身份和访问管理子系统,下称用户IAM(Identity and Access Management),旨在为OpenHarmony提供统一用户身份凭据信息管理和用户身份认证框架能力,支持多用户分别设置认证凭据信息,并根据用户设置的认证凭据信息提供用户身份认证功能,支撑锁屏等安全场景。同时,用户IAM子系统也提供API,支持三方开发者调用系统提供的身份认证能力来实现业务对用户的访问控制要求。 **图1** 子系统架构图 -用户IAM子系统逻辑架构 +![](figures/用户IAM子系统逻辑架构.png) 用户IAM子系统分为统一用户认证框架和认证执行器两个部分,其中**统一用户认证框架**部分包含: diff --git a/zh-cn/release-notes/OpenHarmony-v3.1-release.md b/zh-cn/release-notes/OpenHarmony-v3.1-release.md index 046c3317e6a37dd20492f8b4f5e81284c49ab3ba..bc1018830bfcb168b3f56b7767cebd4ecc851213 100755 --- a/zh-cn/release-notes/OpenHarmony-v3.1-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1-release.md @@ -190,7 +190,7 @@ repo forall -c 'git lfs pull' API变更请参考: -_[API差异报告](api-change/v3.1-Release/readme.md)_ +_[API差异报告](api-change/v3.1-Release/Readme-CN.md)_ ### 芯片及开发板适配 @@ -215,7 +215,7 @@ _[API差异报告](api-change/v3.1-Release/readme.md)_ | ArkUI | [拖拽](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Drag) | 本示例主要展示了拖拽操作的功能。 | eTS | | ArkUI | [动画](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/ArkUIAnimation) | 本示例通过点击按钮触发动画,向用户展示属性动画与显示动画的效果。 | eTS | | 数据管理 | [分布式数据库-结果集和谓词查询](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery) | 本示例展示了分布式数据管理中,如何通过构建query对象, 查询kvstore中的数据,获取结果集。 | eTS | -| 数据管理 | [关系型数据库](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb) | 本示例展示了在eTS中关系型数据库的使用,包括增、删、改、查等操作。 | eTS | +| 数据管理 | [关系型数据库](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) | 本示例展示了在eTS中关系型数据库的使用,包括增、删、改、查等操作。 | eTS | | 事件 | [后台代理提醒](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) | 本示例通过模拟闹钟来展示后台代理提醒的使用方法。 | eTS | | 事件 | [事件通知](https://gitee.com/openharmony/app_samples/tree/master/Notification/Emitter) | 本示例主要展示进程内事件通知,用户通过选择对应商品并提交订单后在订单列表显示所选商品。 | eTS | | 通信与连接 | [RPC通信](https://gitee.com/openharmony/app_samples/tree/master/Communication/RPC) | 本示例展示了同一设备中前后台的数据交互,用户前台选择相应的商品与数目,后台计算出结果,回传给前台展示。 | eTS | @@ -248,10 +248,10 @@ _[API差异报告](api-change/v3.1-Release/readme.md)_ | ISSUE单 | 问题描述 | | -------- | -------- | | [I4MGJM](https://gitee.com/openharmony/drivers_peripheral/issues/I4MGJM) | 【hdf/camera】RK3568单板跑camera HDI用例失败 | -| [I4OECR](https://gitee.com/openharmony/ark_js_runtime/issues/I4OECR) | XTS运行报ark异常栈(低概率问题) | -| [I4OBTW](https://gitee.com/openharmony/aafwk_standard/issues/I4OBTW) | 全量执行XTS用例,安装应用后出现批量aa start 失败,影响社区流水线稳定性测试 | -| [I4OLHF](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLHF?from=project-issue) | 【ArkUI子系统】 由进程com.amsst.amsMissionSnapshotTest导致测试进程异常 | -| [I4OLUK](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLUK) | 【ArkUI子系统】 由进程com.ohos.systemui导致进程栈异常 | +| I4OECR | XTS运行报ark异常栈(低概率问题) | +| I4OBTW | 全量执行XTS用例,安装应用后出现批量aa start 失败,影响社区流水线稳定性测试 | +| I4OLHF | 【ArkUI子系统】 由进程com.amsst.amsMissionSnapshotTest导致测试进程异常 | +| I4OLUK | 【ArkUI子系统】 由进程com.ohos.systemui导致进程栈异常 | ## 遗留缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md index 1a05a0e689fb773071c779e82d03e3be67a48889..1819cdbe09524576f272ccba0dd36b38790b2de9 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md @@ -173,7 +173,7 @@ ArkUI支持AbilityComponent组件将应用界面(Ability)作为控件嵌入 ### API变更 -_[API差异报告](api-change/v3.2-beta1/readme.md)_ +_[API差异报告](api-change/v3.2-beta1/Readme-CN.md)_ ### 芯片及开发板适配 diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md index 58f46c6929ab2f5cbcdeb4a0f3340e4cce3de5a3..16c8318d068221441622c4b6ac881424c84c6bde 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md @@ -170,7 +170,9 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 | Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。
主要涉及如下需求:
I5JPMG 【request部件】【download】后台任务通知
I5NXHK 【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口
I5NG2X 【theme_screenlock部件】支持特定系统应用请求锁定屏幕
I5IU1Z  支持向剪贴板数据增加图片内容的数据项
I5OGA3  支持设备级的跨设备剪贴板开关
I5NMKI 【pasteboard部件】支持向剪贴板数据增加二进制数据
I5MAMN  支持剪贴板数据范围限制在应用内
I5OX20 【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | | ArkUI子系统 | ArkUI组件能力增强;资源、媒体查询能力增强;内存、性能优化;DFX能力增强;工具链能力增强。
主要涉及如下需求:
I5IZZ7 【ace_engine_standard部件】panel组件支持单独设置每个角的borderRadius
I5JQ1R 【ace_engine_standard部件】支持图片复制粘贴
I5JQ3F 【ace_engine_standard部件】输入框能力增强
I5JQ3J 【ace_engine_standard部件】stack组件新增事件拓传机制
I5JQ54 【ace_engine_standard部件】指定控件获取焦点
I5MX7J 【ace_engine_standard部件】list列表支持左滑/右滑及回弹效果
I5MWS0 【ace_engine_standard部件】panel组件弹出高度通知给开发者
I5IZVY 【ace_engine_standard部件】键鼠接入时支持组件刷新
I5JQ5Y 【ace_engine_standard部件】走焦能力增强
I5IY7K 【新增需求】【ace_engine_standard部件】主题能力支持
I5MWTB 【ace_engine_standard部件】媒体查询支持vp查询
I5IZU9 【ace_engine_standard部件】ui_service常驻内存优化
I5JQ26 【ace_engine_standard部件】Vsync请求机制流程优化
I5JQ2O 【ace_engine部件】公共资源预加载
I5JQ2D 【ace_engine_standard部件】Move事件重采样优化
I5IZXS 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZYG 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZX0 【toolchain部件】编译支持解析$r新增bundleName和moduleName参数
I5J09I 【toolchain部件】\@Builder 支持export导出 | NA | +API变更请参考: +[*API差异报告*](api-change/v3.2-beta3/Readme-CN.md) ### 芯片及开发板适配 diff --git a/zh-cn/release-notes/api-change/v3.1-Release/readme.md b/zh-cn/release-notes/api-change/v3.1-Release/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.1-Release/readme.md rename to zh-cn/release-notes/api-change/v3.1-Release/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md index 4c7289ed1c70c6171775bf34f9701689e94e5792..39a5affa00e6649dc1ebf3d54d2311bb33e7813f 100644 --- a/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md +++ b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md @@ -18,4 +18,39 @@ **关键的接口/组件变更** -无 \ No newline at end of file +无 + +### 状态变量多种数据类型声明使用限制。 + +状态变量比如@State、@Provide、 @Link和@Consume等,定义数据类型时,只能同时由简单数据类型或对象引用数据类型其中一种构成。 + +示例: + +```ts +@Entry +@Component +struct Index { + //错误写法: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(`${ this.message }`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +**变更影响** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,编译报错提示不支持。 + +**关键的接口/组件变更** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,需修改为只含有其中一种,如上述示例代码所示。 \ No newline at end of file diff --git a/zh-cn/release-notes/api-change/v3.2-beta1/readme.md b/zh-cn/release-notes/api-change/v3.2-beta1/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.2-beta1/readme.md rename to zh-cn/release-notes/api-change/v3.2-beta1/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.2-beta2/readme.md b/zh-cn/release-notes/api-change/v3.2-beta2/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.2-beta2/readme.md rename to zh-cn/release-notes/api-change/v3.2-beta2/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md b/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md index b218e9aecd626766f51f3e1a2b5249f0b53a6762..a655be51c328a29689b273121e163a455888959a 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md +++ b/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md @@ -55,4 +55,4 @@ OpenHarmony应用沙箱组件 ![](figures/compile-change2-1.png) -![](figures/compile-change2-2.png) \ No newline at end of file +![](figures/compile-change2-2.png) diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/readme.md b/zh-cn/release-notes/api-change/v3.2-beta3/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.2-beta3/readme.md rename to zh-cn/release-notes/api-change/v3.2-beta3/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md b/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md index 48b3fb3ed9d96a59e63451b2aa1010d5298c3cda..411ee5c31b0bbafb237fae401acf30963693cc49 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md +++ b/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md @@ -172,6 +172,41 @@ FA模型下的公共模块变量共享之前是作为需求交付的,在中间 无 +### 状态变量多种数据类型声明使用限制。 + +状态变量比如@State、@Provide、 @Link和@Consume等,定义数据类型时,只能同时由简单数据类型或对象引用数据类型其中一种构成。 + +示例: + +```ts +@Entry +@Component +struct Index { + //错误写法: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(`${ this.message }`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +**变更影响** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,编译报错提示不支持。 + +**关键的接口/组件变更** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,需修改为只含有其中一种,如上述示例代码所示。 + ## 全球化子系统 ### 针对color.json中颜色值,增加合法性校验 diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md b/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md index 7cc610cb724ef4aaa126750f3f4781028cc5de96..f905b19e94e376e0abaf0e50718ddfb5db31320a 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md +++ b/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md @@ -36,4 +36,6 @@ OpenHarmony 3.2 Beta3版本相较于OpenHarmony 3.2 Beta2版本,电源服务 | system.brightness | GetBrightnessOptions | complete?: () => void; | 废弃 | | system.brightness | GetBrightnessOptions | fail?: (data: string, code: number) => void; | 废弃 | | system.brightness | GetBrightnessOptions | success?: (data: BrightnessResponse) => void; | 废弃 | -| system.brightness | BrightnessResponse | value: number; | 废弃 | \ No newline at end of file +| system.brightness | BrightnessResponse | value: number; | 废弃 | +| ohos.batteryInfo | batteryInfo | ohos.batteryinfo -> ohos.batteryInfo | 模块名修改 | +